/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.business;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.tools.json.JSONUtil;
import net.dgg.dggcloud.core.cache.CacheManager;
import net.dgg.dggcloud.core.constants.Constants;
import net.dgg.dggcloud.core.json.JsonUtil;
import net.dgg.dggcloud.core.util.ConfigLoader;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.pagination.PageData;
import net.dgg.dggcloud.service.dao.organization.OrganizationDao;
import net.dgg.dggcloud.service.entity.org.OrganizationEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.*;
import net.dgg.dggcloud.service.jrcrm.dao.business.BusinessDao;
import net.dgg.dggcloud.service.jrcrm.dao.business.BusinessRecordDao;
import net.dgg.dggcloud.service.jrcrm.dao.cms.WorkDayDao;
import net.dgg.dggcloud.service.jrcrm.dao.customer.ContactDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.*;
import net.dgg.dggcloud.service.jrcrm.entity.cms.*;
import net.dgg.dggcloud.service.jrcrm.entity.customer.*;
import net.dgg.dggcloud.service.jrcrm.service.cms.*;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import net.dgg.dggcloud.service.jrcrm.service.customer.DepartmentCustomerService;
import net.dgg.dggcloud.service.jrcrm.service.customer.WhiteListService;
import net.dgg.dggcloud.service.jrcrm.service.customer.WidelyResourceService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.ContactApiService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.CustomerApiService;
import net.dgg.dggcloud.service.jrcrm.service.orf.OrderService;
import net.dgg.dggcloud.service.jrcrm.utils.*;
import net.dgg.dggcloud.service.jrcrm.vo.BusinessAddVo;
import net.dgg.dggcloud.service.jrcrm.vo.HttpResult;
import net.dgg.dggcloud.service.service.RoleService;
import net.dgg.dggcloud.service.service.organization.OrganizationService;
import net.dgg.dggcloud.service.service.user.UserService;
import net.dgg.framework.tac.mq.rabbitmq.queue.DggMessageSendUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.sf.json.util.JSONUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @ClassName 〈BusinessService>
 * @Description
 * @Author 朱永波
 * @Date 2017/11/3 11:42
 */
@Service
public class BusinessService extends BaseService {
    @Resource
    private NJCodeUtil njCodeUtil;
    @Autowired
    private HttpTools httpCon;
    @Resource
    private CustomerApiService customerApiService;
    @Resource
    private RuleConfigService ruleConfigService;
    @Resource
    private ContactApiService contactApiService;
    @Resource
    private BillNumberRuleService billNumberService;
    @Resource
    private UserService userService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private BusinessDao businessDao;
    @Resource
    private CustomerRecordService customerRecordService;
    @Resource
    private ContactDao contactDao;
    @Resource
    private BusinessAllotCountService businessAllotCountService;
    @Resource
    protected MessageService messageService;
    @Resource
    private RoleService roleService;
    @Resource
    private DepartmentCustomerService departmentCustomerService;
    @Resource
    private TreeBookService treeBookService;
    @Resource
    private WidelyResourceService widelyResourceService;
    @Resource
    private WhiteListService whiteListService;

    @Resource
    private SourceBusinessService sourceBusinessService;
    @Resource
    private CustomerService customerService;
    @Resource
    private OrderService orderService;
    @Resource
    private BusinessAllotDeptCountService businessAllotDeptCountService;
    @Resource
    private DeptSetService deptSetService;
    @Resource
    private BusinessReferralService businessReferralService;
    @Resource
    private TypeCostService typeCostService;
    @Resource
    private VipCountService vipCountService;
    @Resource
    private WorkDayDao workDayDao;
    @Resource
    private BusinessDxService businessDxService;

    private OrganizationDao organizationDao;

    /**
     * mindo 查询Business对象。
     *
     *
     *
     */
    public Business getMinDaoBisiness(Long id) {
        Map singMap = new HashMap();
        singMap.put("busId", Long.valueOf(id));
        return businessDao.getBusinessById(singMap);
    }

    /**
     * 已分配记录条数</br>
     *
     * @param map </br>
     * @return 记录 </br>
     */
    public Integer countBusinessAlreadyRecordByMap(Map map) {
        return businessDao.countBusinessAlreadyRecordByMap(map);
    }

    /**
     * 已分配List<Map></br>
     *
     * @param map</br>
     * @return 集合</       br>
     */
    public List<Map> listBusinessAlreadyRecordByMap(Map map) {
        return businessDao.listBusinessAlreadyRecordByMap(map);
    }

    /**
     * 审核记录导出List<Map></br>
     *
     * @param map</br>
     * @return 集合</       br>
     */
    public List<Map> listBusinessRecordExcelByMap(Map map) {
        return businessDao.listBusinessRecordExcelByMap(map);
    }

    /**
     * 审核记录count<Map></br>
     *
     * @param map</br>
     * @return 集合</       br>
     */
    public Integer countBusinessAuditRecordByMap(Map map) {
        return businessDao.countBusinessAuditRecordByMap(map);
    }

    /**
     * 已签单记录条数</br>
     *
     * @param map </br>
     * @return 记录 </br>
     */
    public Integer countOrderBusinessByMap(Map map) {
        return businessDao.countOrderBusinessByMap(map);
    }

    /**
     * 已签单List<Map></br>
     *
     * @param map</br>
     * @return 集合</       br>
     */
    public List<Map> listOrderBusinessByMap(Map map) {
        return businessDao.listOrderBusinessByMap(map);
    }

    /**
     * 根据条件统计商机数量
     *
     * @param map
     * @return
     */
    public Integer countBusinessByMap(Map map) {
        return businessDao.countBusinessByMap(map);
    }

    /**
     * 跟进中的商机列表，因为查询sql的原因，单独对这个列表写了一个sql
     *
     * @param map
     * @return
     */
    public List<Map> listFollowingBusiness(Map map) {
        return businessDao.listFollowingBusiness(map);
    }

    /**
     * 根据条件查询商机列表
     *
     * @param map
     * @return
     */
    public List<Map> listBusinessByMap(Map map) {
        return businessDao.listBusinessByMap(map);
    }

    /**
     * 根据条件查询待分配商机列表
     *
     * @param map
     * @return
     */
    public List<Map> listWaitBusinessByMap(Map map) {
        return businessDao.listWaitBusinessByMap(map);
    }

    /**
     * 根据条件查询待分配商机列表 Test
     *
     * @param map
     * @return
     */
    public List<Map> listWaitBusinessTestByMap(Map map) {
        return businessDao.listWaitBusinessTestByMap(map);
    }

    /**
     * 根据id获取商机
     *
     * @param busId
     * @return
     */
    public Business getBusinessById(Long busId) {
        return repository.get(Business.class, busId);
    }

    /**
     * 根据id获取商机
     *
     * @param busNo
     * @return
     */
    public Business getBusinessByNo(String busNo, Business business) {
        return repository.findUniqueByProperty(Business.class, "no", business.getNo());
    }

    /**
     * 保存商机实体
     *
     * @param business
     * @return
     */
    public void updateBusiness(Business business) {
        repository.saveOrUpdate(business);
    }

    /**
     * 上门操作备注
     *
     * @param business
     * @return recoedType 当前操作
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateSmBusiness(Business business, String recoedType) {
        saveBusinessRecord(business, recoedType, business.getLastFollowRecordContent(), business.getFollowerId(), null, null);
        repository.saveOrUpdate(business);
    }

    /**
     * 新增商机。资源端、商务个人、广泛资源转化、白名单、新媒体接口都使用该方法新增商机
     *
     * @param reqParam 页面参数
     * @param business 页面传入的商机信息
     * @param user     当前操作用户
     * @param addType  新增类型
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Long saveAddNewBusiness(Map reqParam, Business business, User user, String addType) {
        if (null == business) {
            throw new BizException("商机为空，无法操作", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == addType) {
            throw new BizException("新增类型为空，无法操作", 10001);
        }
        if (null == user) {
            throw new BizException("新增人为空，无法操作", 10001);
        }
        String areaName = reqParam.get("areaName") == null ? "" : reqParam.get("areaName").toString();
        if (StringUtils.isBlank(areaName)) {
            throw new BizException("业务区域为空，无法操作", 10001);
        }
        String contactWay = reqParam.get("contactWay") == null ? "" : reqParam.get("contactWay").toString();
        Long customerId = business.getCustomerId();
        Long businessId = keyWorker.nextId();
        business.setId(businessId);
        business.setAddTypeCode(addType);
        String customerPhone = business.getCustomerPhone();

        Customer customer = null;
        // 判断是否传入客户的id，如果有，则从数据库中找,没有再根据电话号码和类型查找
        if (null != customerId) {
            customer = customerApiService.getCustomerById(customerId);
        }
        if (null == customer) {// 根据id没有查到客户，再根据号码去查
            if (StringUtils.isBlank(contactWay)) {
                throw new BizException("客户联系号码类型不能为空", 10001);
            }
            if (StringUtils.isBlank(customerPhone)) {
                throw new BizException("客户号码不能为空", 10001);
            }
            Map param = new HashMap();
            param.put("contactWay", contactWay);
            param.put("customerNumber", customerPhone);
            List<Map> cusList = customerApiService.queryCustomerListByParams(param);
            if (null != cusList && !cusList.isEmpty()) {
                customer = customerApiService.getCustomerById(Long.valueOf(cusList.get(0).get("id").toString()));
            }
        }

        // 资源端新增计算成本

//			Long cost = getCosts(business.getBusinessOrganizationId()+"",business.getTypeCode(),business.getOrigincodeType());
//			if(cost.longValue()>1){
//				business.setIsCost("yes");
//				business.setCostPrice(cost.intValue());
//			}else{
//				business.setIsCost("CBJSFS_NO");
//				business.setCostPrice(cost.intValue());
//			}
        String businessType = "";
        // 如果表单资源是 2 3 4 5 类

        if (null != business.getOrigincodeType()
                && (business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_1) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_3)
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_4) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_5) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_10) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_11) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_12))
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_13) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_14)) {
            String place = treeBookService.queryTreeBookByCode(business.getBusinessOrganizationId().toString()).getExt4();
            Map newPriceMap = new HashMap();
            newPriceMap.put("busCode", "BUS_YT_DK");
            newPriceMap.put("placeCode", "BUS_SOR_PLACE_" + place);
            newPriceMap.put("typeCode", business.getTypeCode()); // 业态CODE
            newPriceMap.put("type", businessType);
            newPriceMap.put("tel", customerPhone);
            newPriceMap.put("city", place);
            newPriceMap.put("originType", business.getOrigincodeType());
            Map priceMap = getCostPriceByOriginType(newPriceMap);
            Map ob = (Map) priceMap.get("data");
            if (priceMap.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                // throw new BizException(priceMap.get("msg").toString(), 10001);
                business.setIsCost("yes");// 需要计算成本
                business.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
            } else {
                business.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
                business.setIsCost("CBJSFS_NO");// 不需要计算成本
            }
        } else {
            business.setIsCost("CBJSFS_NO");// 不需要计算成本
        }
        String opportunitytypeCode = BusinessConstant.BUS_OPP_1;
        String busOperate = CustomerRecordConstant.BUS_OPERATE_NEW;
        Map cus = new HashMap();

        cus.put("name", business.getCustomerName());
        cus.put("customerNumber", business.getCustomerPhone());
        cus.put("contactWay", contactWay);
        cus.put("customerType", 1);
        cus.put("age", reqParam.get("age"));
        cus.put("address", reqParam.get("address"));
        cus.put("registeredResidence", reqParam.get("registeredResidence"));
        cus.put("email", reqParam.get("email"));
        cus.put("maritalStatus", reqParam.get("maritalStatus"));
        cus.put("birthday", reqParam.get("birthday"));
        cus.put("idCard", reqParam.get("idCard"));
        cus.put("sex", reqParam.get("sex"));
        cus.put("eduBackground", reqParam.get("eduBackground"));
        cus.put("origin", business.getOriginCode());
        cus.put("originName", reqParam.get("originCodeName"));
        cus.put("User", user);
        cus.put("customerAttr", reqParam.get("customerAttr"));
        cus.put("contacts", reqParam.get("contacts"));
        cus.put("business", business);
        // 没有则新增
        if (null == customer) {
//			Map  attrMap = new HashMap();
//			attrMap.put("customerPhone",cus.get("customerNumber"));
//			Query query = repository.getSession().createQuery("From CustomerForm where phone ='"+customerPhone+"'");
//			if(query.list().size()>0) {
//				CustomerForm cf = (CustomerForm) query.list().get(0);
//				business.setLoanAmount(cf.getMoney()*100);;
//			}
            // 客户新增

            Map cusMap = customerApiService.saveCustomer(cus);
            customer = (Customer) cusMap.get("data");
            if (BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(addType)) {
                opportunitytypeCode = BusinessConstant.BUS_OPP_3;
            }
        } else {
            // 客户存在则进行商机判重
            // 统计商机状态不为退单且没有在事业部库、无效库都数量
            Map existed = new HashMap();
            existed.put("customerId", customer.getId());
            existed.put("notInBusinessLocation", "6");
            String centerIds = null;
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
            if (!business.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_5)) { //资源端新建
                //资源端新建
                if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                    existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
                } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                    existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
                } else {//全集团
                }
            } else {
                if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                    existed.put("businessOrganizationId", organizationService.getOrganizationDepartmentId(user.getOrgId()) + "");
                } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                    //	Long orgId = organizationService.getOrganizatioComploy(business.getBusinessOrganizationId());
                    existed.put("businessOrganizationId", organizationService.getOrganizationDepartmentId(user.getOrgId()) + "");
                } else {//全集团

                }
            }
            List<Map> list = businessDao.listBusinessByMap(existed);
            if (null != list && !list.isEmpty()) {
                // 客户商机跟进人为当前操作人，商机状态为已成单则可以新建商机，其他一律不能新建商机
                existed.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                //String days = ruleConfigService.getRuleConfigByMap(1L, "GZ_BUS_SIGNED_ADD");
                String day = null;
                if (NumberUtils.toInt(tb.getExt1()) != 0) {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()) + 1);
                    day = workDayDao.queryBeforeDate(existed);
                } else {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()));
                }

                boolean ex = false; // false 可以新建商机
                boolean isOrder = false;  // 是否已经签单
                for (Map map : list) {
                    boolean businessStatus = BusinessConstant.BUS_STATUS_SIGNED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(String.valueOf(map.get("businessStatus")));
                    if (business.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_5)) {//商务自开发
                        if (NumberUtils.toInt(map.get("businessLocation") + "") != 2 && NumberUtils.toInt(map.get("businessLocation") + "") != 5) {
                            ex = true;
                            break;
                        }
                        Map typeMap = organizationService.getOrganizationDepartmentCenterMap(NumberUtils.toLong(map.get("followerOrganizationId") + ""));
                        Map userMap = organizationService.getOrganizationDepartmentCenterMap(user.getOrgId());
                        String busOrgType = typeMap.get("type") == null ? "" : typeMap.get("type").toString();//中心类型
                        String orgType = userMap.get("type") == null ? "" : userMap.get("type").toString();//商机所属中心类型
                        if (orgType.equals(busOrgType) && busOrgType.equals(OrgConstant.ORG_TYPE_4)) {
                            if (businessStatus) {
                                isOrder = true;
                            } else {
                                ex = true;
                                break;
                            }
                        } else if (orgType.equals(busOrgType) && busOrgType.equals(OrgConstant.ORG_TYPE_5)) {
                            if (businessStatus) {
                                isOrder = true;
                            } else {
                                ex = true;
                                break;
                            }
                        } else if (orgType.equals(busOrgType) && !busOrgType.equals(OrgConstant.ORG_TYPE_5) && !busOrgType.equals(OrgConstant.ORG_TYPE_4)) {
                            if (businessStatus) {
                                isOrder = true;
                            } else {
                                ex = true;
                                break;
                            }
                        } else {
                            ex = false;
                        }
                    } else {
                        if (businessStatus) {
                            isOrder = true;
                        } else {
                            ex = true;
                            break;
                        }
                    }
                    //判断已签单商机是否已过可以新建商机的时间
                    if (isOrder) {
                        if (map.get("orderTime") != null && StringUtils.isNotEmpty(day)) {
                            String orderTime = map.get("orderTime").toString();
                            int i = DateUtil.compare_date(day + " 00:00:00", orderTime);
                            if (i == 1) {
                                ex = false;
                            } else {
                                ex = true;
                                break;
                            }
                        }

                    } else {
                        ex = false;
                    }


                }
                BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");

            }
            // 判断是否是商务角色
            if (roleService.userHasRole(user, "bus_advisor")) {
                // 转介绍商机新增
                if (null != business.getIsReferral() && 1 == business.getIsReferral()) {
                    // 转介绍修改接收人
                    BusinessReferral oldBusinessReferral = this.repository.get(BusinessReferral.class, Long.parseLong(reqParam.get("rid").toString()));
                    Business oldBusiness = this.repository.get(Business.class, Long.parseLong(reqParam.get("rid").toString()));
                    BusinessReferral businessReferral = new BusinessReferral();
                    if (null != oldBusinessReferral) {
                        businessReferral.setReceiveUserName(user.getName() + user.getLoginName());
                        businessReferral.setReceiveOrgId(user.getOrgId());
                        businessReferral.setReceiveUserId(user.getId());
                        businessReferral.setId(business.getId());
                        businessReferral.setIsReceive(1);
                        businessReferral.setReferralTime(oldBusinessReferral.getReferralTime());
                        businessReferral.setRewardWay(oldBusinessReferral.getRewardWay());
                        businessReferral.setReturnNum(oldBusinessReferral.getReturnNum());
                        businessReferral.setCurrentReturnOrgId(oldBusinessReferral.getCurrentReturnOrgId());
                        businessReferral.setCreateUser(user);
                        // businessReferral.setCreateTime(oldBusinessReferral.getCreateTime());
                        // businessReferral.setCreaterId(oldBusinessReferral.getCreaterId());
                        // businessReferral.setCreaterOrgId(oldBusinessReferral.getCreaterOrgId());
                        // businessReferral.setCreaterName(oldBusinessReferral.getCreaterName());
                        businessReferral.setUpdaterUser(user);
                        businessReferral.setCurrentReturnUserId(oldBusinessReferral.getCurrentReturnUserId());
                        businessReferral.setCurrentReturnUserName(oldBusinessReferral.getCurrentReturnUserName());
                        businessReferral.setRemark(oldBusinessReferral.getRemark());
                        businessReferral.setReferralRed(oldBusinessReferral.getReferralRed());
                        businessReferral.setRed(oldBusinessReferral.getRed());
                        businessReferral.setTcProportion(oldBusinessReferral.getTcProportion());
                        businessReferral.setIsFa(oldBusinessReferral.getIsFa());
                        businessReferral.setFaTime(oldBusinessReferral.getFaTime());
                        businessReferral.setTcred(oldBusinessReferral.getTcred());
                        businessReferral.setReturnTime(oldBusinessReferral.getReturnTime());
                        businessReferral.setCostomerDemand(oldBusinessReferral.getCostomerDemand());
                        businessReferral.setPerformanceProportion(oldBusinessReferral.getPerformanceProportion());
                        businessReferral.setReferralUserName(oldBusinessReferral.getReferralUserName());
                        businessReferral.setReferralOrgId(oldBusinessReferral.getReferralOrgId());
                        businessReferral.setReferralUserId(oldBusinessReferral.getReferralUserId());
                        businessReferral.setReferralAuditStatus(oldBusinessReferral.getReferralAuditStatus());
                        businessReferral.setCustomerId(customer.getId());
                        businessReferral.setCreateType(2);
                        businessReferral.setReferralOrganizationId(oldBusinessReferral.getReferralOrganizationId());
                        businessReferral.setReferralOrganizationName(oldBusinessReferral.getReferralOrganizationName());

                        this.repository.saveOrUpdate(businessReferral);
                        // this.repository.delete(oldBusinessReferral);
                        if (null != oldBusiness) {
                            business.setIsReturn(oldBusiness.getIsReturn());
                        }
                    }
                }
            }

            cus.put("id", customer.getId());
            cus.put("contactWay", customer.getContactWay());
            customerApiService.updateCustomer(cus);
            // 客户存在且当前新增类型为自开发，那么商机类型就应该为二次开发
            if (BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(addType)) {
                opportunitytypeCode = BusinessConstant.BUS_OPP_2;
            }
        }

        business.setCustomerAttr(customer.getCustomerAttrFlag());
        business.setCustomerId(customer.getId());
        business.setCustomerNo(customer.getNo());
        business.setCustomerWay(customer.getContactWay());
        business.setCreateUser(user);
//        if (business.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_4) || business.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_1)) {
//            business.setBusinessStatus(BusinessConstant.BUS_STATUS_AUTO_NEW);// 待自动分配
//        }
        if(null!=business.getBusinessStatus()&&business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_AUTO_NEW)){
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_AUTO_NEW);// 待自动分配
        }
        if(null==business.getBusinessStatus()){
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_NEW);// 待分配
        }
        // 默认为0的字段
        business.setIsImportant(0);
        business.setIsVip(0);
        business.setFollowTimes(0);

        // 商机类型，资源端为公司商机，商务自开发为自主开发，但客户存在则为二次开发
        business.setOpportunitytypeCode(opportunitytypeCode);
        // 新增表单资源按金额确定来源渠道类型 2018-09-06
//		if(business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_1)){//公司商机
//			customerApiService.setBusinessOrigincodeType(business,customer);
//		}

        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
        }

        // 判断商机的新增方式
        if (!BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(addType)) {// 非商务自开发
            if (null == business.getBusinessOrganizationId()) {
                throw new BizException("请选择受理事业部", 10001);
            }
            // 是否计算成本，根据渠道查询计算成本的方式及值
//			if (null != business.getIsCost() && business.getIsCost().equals("yes")) {
//				ChannelCost coc = null;
//				List<ChannelCost> list = repository.findByProperty(ChannelCost.class, "channelCode", business.getOriginCode());
//				if (null != list && !list.isEmpty()) {
//					coc = list.get(0);
//				}
//				if (null == coc || coc.getStatus() != 1) {//不存在或未启用的都不计算成本
//					business.setIsCost("CBJSFS_NO");
//					business.setCostPrice(0);
//				} else {
//					business.setIsCost(coc.getCostType());
//					business.setCostPrice(coc.getCost());
//				}
//			}
            business.setBusinessLocation(BusinessConstant.BUS_STORE_SOURCE);// 资源库
        } else {
            busOperate = CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP;
            business.setFirstFollowerId(user.getId());
            business.setFirstFollowerOrganizationId(user.getOrgId());
            business.setFollowerName(user.getName() + user.getLoginName());
            business.setFollowerId(business.getFirstFollowerId());
            business.setDistributionTime(business.getCreateTime());// 本次分配时间
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);// 跟进中
            if (null == user.getOrgId()) {
                throw new BizException("你还未设置资源部门，请联系管理员进行设置！", 10001);
            }

            Long orgId = organizationService.getOrganizationDepartmentId(user.getOrgId());
            if (orgId < 0) {
                throw new BizException("未找到你当前所在事业部，请联系管理员进行设置！", 10001);
            }
            business.setBusinessOrganizationId(orgId);// 当前新建人的事业部
            business.setFollowerOrganizationId(user.getOrgId());// 当前新建人的部门
            business.setWayCode(BusinessConstant.BUS_WAY_CODE_2);// 自开发
        }

        business.setBusinessOperate(busOperate);// 当前操作
        // 判断是否需要对外部来源，如广泛资源的数据做处理
        if (business.getWidelyId() != null) {
            if (1 == business.getWidelyType()) {
                // 做广泛资源的处理
                Map widelyParam = new HashMap();
                widelyParam.put("widelyId", business.getWidelyId());
                widelyParam.put("month", reqParam.get("widelyMonth"));
                Map wr = widelyResourceService.queryWidelyResourceById(widelyParam);
                if (null != wr) {
                    if (null != wr.get("turnbusid")) {
                        throw new BizException("广泛资源已被转化，不可再次转化", 10001);
                    }
                    widelyParam.put("busId", business.getId());
                    widelyResourceService.updateWidelyResourceBusId(widelyParam);
                }
            } else if (2 == business.getWidelyType()) {
                SourceBusiness sb = sourceBusinessService.getById(business.getWidelyId());
                BizExceptionUtil.isException(sb.getStatus() != 3 && sb.getStatus() != 0, "待筛选资源状态更已更新，请刷新后再试");
                sb.setUpdaterUser(user);
                sb.setStatus(1);
                sb.setResult("");
                repository.saveOrUpdate(sb);
            }

        }

        // 从事业部删除客户数据，更新白名单数据
        DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(customer.getId());
        if (null != dc) {
            // 事业部客户资源拾回限制，因为事业部客户暂时未对商务开放，暂时不做限制
            if (opportunitytypeCode.equals(BusinessConstant.BUS_OPP_2)) {
//                String limit = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_SYB_1");//事业部拾回条数从配置中拿
//                if (StringUtils.isNotBlank(limit)) {
//                    //查找商务今天新建了多少条事业部拾回的商机，对比事业部的事业部拾回条数限制
//                    Map existed = new HashMap();
//                    existed.put("createrId", user.getId());
//                    existed.put("screateTime", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
//                    existed.put("ecreateTime", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
//                    existed.put("opportunitytypeCode", BusinessConstant.BUS_OPP_4);
//                    int all = businessDao.countBusinessByMap(existed);
//                    BizExceptionUtil.isException(all >= Integer.valueOf(limit), "【" + TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId()) + "】每天只允许拾回" + limit + "条客户，你今日已拾回" + all + "条，不能再拾回！");
//                }
                business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_4);// 类型改为事业部拾回
            }
            if (dc.getPushTime() != null) {
                Map whiteListMap = new HashMap();
                String pushMonth = DateUtil.dateToString(dc.getPushTime(), "yyyy-MM-dd");
                whiteListMap.put("month", pushMonth);
                whiteListMap.put("deptCusId", dc.getId());
                // 查询所有白名单表
                List<WhiteList> wl = whiteListService.queryWhiteListByParam(whiteListMap);
                if (null != wl && wl.size() > 0) {
                    for (WhiteList whiteList : wl) {
                        whiteList.setUpdaterUser(user);
                        Integer status = whiteList.getPushUserId().longValue() == user.getId().longValue() ? 2 : 3;
                        whiteList.setStatus(status);
                        repository.saveOrUpdate(whiteList);
                    }
                }
            }
            repository.delete(dc);
        }
        // 删除无效库中客户相关的数据
        Map imap = new HashMap();
        imap.put("customerId", customer.getId());
        businessDao.deleteInvalidCustomerByMap(imap);

//        User receiver = null;
        if (null != customer.getLastBusId()) {
            Business lastBusiness = repository.get(Business.class, customer.getLastBusId());
            if (null != lastBusiness && BusinessConstant.BUS_STATUS_ORDER_BACK.equals(lastBusiness.getBusinessStatus())) {
                // 所在库为个人库，将强制掉库
                if (BusinessConstant.BUS_STORE_EMP.equals(lastBusiness.getBusinessLocation())) {
                    dropBusiness(lastBusiness, user, CustomerRecordConstant.BUS_OPERATE_BACKORDER_DROP);// 强制掉库
                }
            }
            // 客户的最后一条商机为成单商机，接收人默认为原商务
            if (null != lastBusiness && BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(lastBusiness.getBusinessStatus())) {
//                receiver = repository.get(User.class, lastBusiness.getFollowerId());
                // 所在库为个人库，将强制掉库
                if (BusinessConstant.BUS_STORE_EMP.equals(lastBusiness.getBusinessLocation())) {
                    dropBusiness(lastBusiness, user, CustomerRecordConstant.BUS_OPERATE_ORDER_SUCCESS_DROP);// 强制掉库
                }
            }
        }

        // 资源端是否立即分配
        String allot = reqParam.get("allot") == null ? "" : reqParam.get("allot").toString();
        if ("1".equals(allot) && !BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(addType)) {
//            //判断是否分配原商务
//            String toLastUser = reqParam.get("toLastUser") == null ? "" : reqParam.get("toLastUser").toString();
//            if (!"1".equals(toLastUser)) {//分配给原商务的传值不为1
//                receiver = null;
//            } else {//分配给原商务，需要判断商务是否可接单
//                //判断商务是否可接单
//                isUserCanReceiveBusiness(receiver);
//            }
            allotBusiness(business, null, user, customer.getLevel(), 2, 1);
        }
        // 计算预计掉库时间
        setBusinessWillDropDate(business);

        business.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        String no = billNumberService.updateBillNumberByCode("SJ");// 商机单据号
        business.setNo(no);
        repository.save(business);
        // 写入新增商机的备注日志
//        saveBusinessRecord(business, busOperate, "新增了商机", user.getId(), null, business.getFollowerId());
        saveBusinessRecord(business, busOperate, "新增了商机", user.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());
        // 对选中的产品做处理
        String productIds = reqParam.get("productIdsTemp") == null ? "" : reqParam.get("productIdsTemp").toString();
        if (StringUtils.isNotBlank(productIds)) {
            String[] idArr = productIds.split(",");
            Map newInfo = new HashMap();
            newInfo.put("businessId", businessId);
            for (String s : idArr) {
                newInfo.put("productId", s);
                businessDao.addBusinessProductByMap(newInfo);
            }
        }
        // TODO to xuzhe 抛出商机已添加消息，如果影响到启动，请注释掉该行
//        MessageManager.getMessageManager().publishEvent(PublishMessageExchangeNames.BUSINESS_ADDED, business);

        return businessId;
    }

    /**
     * 商机强制掉库
     *
     * @param lastBusiness 掉库商机
     * @param user         操作人
     * @param dropType     掉库类型，成单掉库或退单掉库
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void dropBusiness(Business lastBusiness, User user, String dropType) {
        lastBusiness.setBusinessLocation(BusinessConstant.BUS_STORE_DEPARTMENT);
        lastBusiness.setBusinessOperate(dropType);
        lastBusiness.setIsVip(0);
        lastBusiness.setIsImportant(0);
        lastBusiness.setLastFollowRecordTime(new Date());
        lastBusiness.setLastFollowRecordContent("客户被开发，商机强制掉库");
        lastBusiness.setLastFollowRecordUser(user.getName() + user.getLoginName());
        lastBusiness.setUpdaterUser(user);
        lastBusiness.setLoseDeptTime(new Date());
        repository.saveOrUpdate(lastBusiness);
        saveBusinessRecord(lastBusiness, dropType, "客户被开发，商机强制掉库", user.getId(), lastBusiness.getFollowerId(), null, lastBusiness.getFollowerOrganizationId(), null,
                lastBusiness.getFollowerName(), "");
        User msgUser = repository.get(User.class, lastBusiness.getFollowerId());
//        messageService.sendMessage(msgUser, user, "你的客户【" + lastBusiness.getCustomerName() + "/" + lastBusiness.getCustomerNo() + "】已经被【" + user.getName() + "】新建了商机，因此客户被强制移交给【" + user.getName() + "】", 2, 1);
        sendBusinessMsg(msgUser, user, "SJ_0003", lastBusiness.getCustomerName(), lastBusiness.getCustomerNo(), user.getName() + user.getLoginName(), user.getName());
    }

    /**
     * 发送商机信息提示
     *
     * @param receiverUser        接收人
     * @param sendUser            发送人
     * @param messageTemplateCode 模版code
     * @param vals                参数
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void sendBusinessMsg(User receiverUser, User sendUser, String messageTemplateCode, String... vals) {
        BizExceptionUtil.isException(null == vals, "短信参数不能为空");
        messageService.sendMessageReady(receiverUser, sendUser, vals, messageTemplateCode);
    }

    /**
     * 保存一般的商机备注信息，即当商机跟进人或状态没有变动时调用该方法
     *
     * @param business      商机信息
     * @param recordType    备注类型
     * @param content       备注内容
     * @param operateUserId 操作人
     * @param oldFollowerId 商机原跟进人
     * @param newFollowerId 商机新跟进人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId) {
        saveBusinessRecord(business, recordType, content, operateUserId, oldFollowerId, newFollowerId, null, null, "", "");
    }

    /**
     * 保存一般的商机备注信息，调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param operateOrgId     操作人部门id
     * @param newFollowerId    新商机跟进人id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessJsonRecord(Business business, String recordType, String content, Long operateUserId, Long operateOrgId, Long newFollowerId, Long newFollowerOrgId,
                                        String newFollowerName) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("toUserId", newFollowerId);// 新的跟进人
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("ext5", business.getCostPrice());// 商机成本
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id
        JSONObject json = new JSONObject();
        if (StringUtils.isNotBlank(newFollowerName)) {
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));

            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName); // 被分配人
            }
            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        } else {
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));
            json.put("inUser", ""); // 被分配人

            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
        }
        if (newFollowerOrgId != null) {
            User u = userService.getUserById(newFollowerId);
            json.put("inUser", u.getName() + "," + u.getLoginName());
        }
        recordMap.put("altJson", JsonUtil.obj2Json(json));
        recordMap.put("newFollowerId", newFollowerId);
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存电销分配的商机备注信息，调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param operateOrgId     操作人部门id
     * @param newFollowerId    新商机跟进人id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessFpJsonRecord(Business business, String recordType, String content, Long operateUserId, Long operateOrgId, Long newFollowerId, Long newFollowerOrgId,
                                          String newFollowerName) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("fromUserId", operateUserId);
        recordMap.put("fromUserOrgId", operateOrgId);
        recordMap.put("toUserId", newFollowerId);// 新的跟进人
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("ext5", business.getCostPrice());// 商机成本
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id

        if (StringUtils.isNotBlank(newFollowerName)) {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));

            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName); // 被分配人
            }
            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        } else {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));
            json.put("inUser", ""); // 被分配人

            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        }
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存一般的PK商机备注信息，调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param operateOrgId     操作人部门id
     * @param newFollowerId    新商机跟进人id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessPkJsonRecord(Business business, String recordType, String content, Long operateUserId, Long operateOrgId, Long newFollowerId, Long newFollowerOrgId,
                                          String newFollowerName) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("toUserId", newFollowerId);// 新的跟进人
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("ext5", business.getPrice());// 商机成本
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id

        if (StringUtils.isNotBlank(newFollowerName)) {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));

            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName); // 被分配人
            }
            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        } else {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));
            json.put("inUser", ""); // 被分配人

            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId())); // 事业

            }
            json.put("count", business.getIsImportant()); // 分配人
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        }
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存二次分配的商机备注信息，调用该方法
     *
     * @param business 商机信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessAgainRecord(Business business, CustomerRecord cr, User user) {
        cr.setToUserId(business.getFollowerId());// 新的跟进人
        net.sf.json.JSONObject jsonarray = net.sf.json.JSONObject.fromObject(cr.getAltJson());
        jsonarray.put("inUser", user.getName() + user.getLoginName());
        cr.setAltJson(JsonUtil.obj2Json(jsonarray));
        customerRecordService.updateCustomerRecord(cr);
    }

    /**
     * 保存有附件的备注调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param oldFollowerId    原商机跟进人id
     * @param newFollowerId    新商机跟进人id
     * @param oldFollowerOrgId 原商机跟进人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param oldFollowerName  原商机跟进人名字
     * @param newFollowerName  新商机跟进人名字
     * @param fileId           附件id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessFileRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId, Long oldFollowerOrgId,
                                        Long newFollowerOrgId, String oldFollowerName, String newFollowerName, String fileId) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("fromUserId", oldFollowerId);// 旧跟进人新的跟进人
        recordMap.put("toUserId", newFollowerId);//
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("ext5", fileId);// 附件id
        recordMap.put("fromUserOrgId", oldFollowerOrgId);// 出库人部门id
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id
        JSONObject json = new JSONObject();
        json.put("count", business.getIsImportant() + ""); // 当前分配次数
        if (StringUtils.isNotBlank(oldFollowerName) || StringUtils.isNotBlank(newFollowerName)) {

            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));
            if (StringUtils.isNotBlank(oldFollowerName)) {
                json.put("outUser", oldFollowerName);
            }
            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName);
                json.put("inUserOrg", TranslateMapUtil.translateOrgName(business.getFollowerOrganizationId()));
                json.put("inUserbzName", TranslateMapUtil.translateOrgName(business.getBusinessOrganizationId()));
            }

        }
        recordMap.put("altJson", JsonUtil.obj2Json(json));
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存有附件的备注调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param newFollowerId    新商机跟进人id
     * @param operateOrgId     操作人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessInvalidRecord2(Business business, String recordType, String content, Long operateUserId, Long operateOrgId, Long newFollowerId, Long newFollowerOrgId,
                                            String newFollowerName) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("toUserId", newFollowerId);// 新的跟进人
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id

        if (StringUtils.isNotBlank(newFollowerName)) {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));

            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName); // 被分配人
            }
            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(organizationService.getOrganizationDepartmentId(newFollowerOrgId))); // 事业

            }
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        }
        recordMap.put("operateUser", operateUserId);
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 返无效调用该方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param newFollowerId    新商机跟进人id
     * @param operateOrgId     操作人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveBusinessInvalidRecord(Business business, User user, String recordType, String content, String operateUserName, Long operateUserId, Long operateOrgId,
                                           Long newFollowerId, Long newFollowerOrgId, String newFollowerName) {
        Map recordMap = new HashMap();
        recordMap.put("tableName", Business.TABLE_NAME);
        recordMap.put("tableId", business.getId());
        recordMap.put("cusId", business.getCustomerId());
        recordMap.put("recordType", recordType);
        recordMap.put("content", content);
        recordMap.put("toUserId", newFollowerId);// 新的跟进人
        recordMap.put("ext1", business.getBusinessStage());// 商机所在库
        recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
        recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
        recordMap.put("ext3", business.getNo());// 商机编号
        recordMap.put("toUserOrgId", newFollowerOrgId);// 入库人部门id

        if (StringUtils.isNotBlank(newFollowerName)) {
            JSONObject json = new JSONObject();
            json.put("createrOrgName", TranslateMapUtil.translateOrgName(business.getCreaterOrgId()));

            if (StringUtils.isNotBlank(newFollowerName)) {
                json.put("inUser", newFollowerName); // 被分配人
            }
            if (StringUtils.isNotBlank(operateUserName)) {
                json.put("outUser", operateUserName);
            }
            if (StringUtils.isNotBlank(operateOrgId == null ? "" : operateOrgId.toString())) {
                json.put("outOrgName", TranslateMapUtil.translateOrgName(operateOrgId)); // 分配人部门
            }
            if (StringUtils.isNotBlank(newFollowerOrgId == null ? "" : newFollowerOrgId.toString())) {
                json.put("inOrgName", TranslateMapUtil.translateOrgName(newFollowerOrgId)); // 被分配人
                json.put("bzName", TranslateMapUtil.translateOrgName(organizationService.getOrganizationDepartmentId(newFollowerOrgId))); // 事业

            }
            recordMap.put("altJson", JsonUtil.obj2Json(json));
        }
        recordMap.put("operateUser", user.getId());
        customerRecordService.saveCustomerRecord(recordMap);
    }

    /**
     * 保存有出入库操作的备注/有商机跟进人变动的应该掉这个方法
     *
     * @param business         商机信息
     * @param recordType       操作类型
     * @param content          备注内容
     * @param operateUserId    操作人id
     * @param oldFollowerId    原商机跟进人id
     * @param newFollowerId    新商机跟进人id
     * @param oldFollowerOrgId 原商机跟进人部门id
     * @param newFollowerOrgId 新商机跟进人部门id
     * @param oldFollowerName  原商机跟进人名字
     * @param newFollowerName  新商机跟进人名字
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveBusinessRecord(Business business, String recordType, String content, Long operateUserId, Long oldFollowerId, Long newFollowerId, Long oldFollowerOrgId,
                                   Long newFollowerOrgId, String oldFollowerName, String newFollowerName) {
        saveBusinessFileRecord(business, recordType, content, operateUserId, oldFollowerId, newFollowerId, oldFollowerOrgId, newFollowerOrgId, oldFollowerName, newFollowerName,
                "");
    }

    /**
     * 是否计算成本
     *
     * @param
     * @return sources 来源渠道
     */
    private Integer iscost(Business business) {
        TreeBook book = treeBookService.queryTreeBookByCode(business.getOriginCode());
        if (null != book && book.getStatus() == 1 && null != book.getType() && book.getType() != 1 && book.getType() != 2)// 来源渠道是否计算成本
        {
            return null;
        } else {
            TreeBook orbook = treeBookService.queryTreeBookByCode(business.getBusinessOrganizationId().toString());
            if (null != orbook && orbook.getStatus() == 1)// 事业部类型是否启用
            {
                if (null != orbook.getCostType() && (orbook.getCostType() == 1 || orbook.getCostType() == 2)) { // 1直营 2 小顶上门
                    Map map = new HashMap();
                    map.put("code", business.getTypeCode());
                    map.put("place", orbook.getExt1());
                    map.put("month", DateUtil.dateToString(new Date(), "yyyy-MM"));
                    TypeCost cost = typeCostService.getTypeCost(map);
                    if (null != cost && null != book && null != book.getType() && book.getType() == 1) { // 来源渠道 表单
                        if (orbook.getCostType() == 1) { // 直营
                            return cost.getFormPrice();
                        }
                        if (orbook.getCostType() == 2) {
                            return cost.getFormPrice();
                        }
                    }
                    if (null != cost && null != book && null != book.getType() && book.getType() == 2) {// 来源渠道 非表单
                        if (orbook.getCostType() == 1) {
                            return cost.getNotFormPrice();
                        }
                        if (orbook.getCostType() == 2) {
                            return cost.getNotFormPrice();
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 商机分配，并写入分配日志，发送提醒短信给商务
     *
     * @param business      被分配的商机
     * @param receiver      商机接收人
     * @param allotUser     分配人，即当前操作人
     * @param customerLevel 客户等级，自动分配时需要传入
     * @param allotType     1人工，2自动 type 1 资源端 2部门
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotBusiness(Business business, User receiver, User allotUser, String customerLevel, int allotType, int type) {

        if (null == receiver) {// 接收人为空，则调用自动分配的接口
            if (null == business.getBusinessOrganizationId()) {
                throw new BizException("商机未选择受理事业部，无法分配", 10001);
            }
            business.setUpdaterUser(allotUser);// 将分配人写入update数据中，用于在界面展示
            JSONObject map = new JSONObject();
            map.put("sjId", business.getId());
            customerLevel = StringUtils.isBlank(customerLevel) ? "0" : customerLevel.trim();
            customerLevel = customerLevel.replace("CUS_KHZZ_STAR_", "");// 等级的格式应该为CUS_KHZZ_STAR_3.5
            BigDecimal lev = new BigDecimal(0);// 默认都是0星资源
            try {
                lev = new BigDecimal(customerLevel);
            } catch (Exception e) {
            }
            map.put("customerLevel", lev.setScale(1, BigDecimal.ROUND_DOWN).doubleValue());
            map.put("orgId", business.getBusinessOrganizationId());
            map.put("userId", allotUser.getId());

//            JSONObject addtionInfo = new JSONObject();
////            addtionInfo.put("allotUserId", allotUser.getId());
////            map.put("addtionInfo", addtionInfo);
            try {
                String rest = HttpRequest.httpPostWithJSON(ConfigLoader.getConfigLoader().getVaule("autodispatchurl").trim(), map);
                Map result = JsonUtil.json2Obj(rest, Map.class);
                if (!result.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                    throw new BizException("自动分配失败，请稍后再试!", 10001);
                }
            } catch (Exception e) {
                throw new BizException("自动分配请求失败，请提醒管理员检查分配服务!", 10001);
            }
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT);// 将当前操作改为进入分配队列

            return;
        }
        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_AUTO_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN)
                && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT)) {
            throw new BizException("商机已完成分配，不能再次分配!", 10001);
        }
        business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(receiver.getId());// 第一次接收人
        business.setFirstFollowerOrganizationId(receiver.getOrgId());// 第一次接收人部门id
        business.setDistributionTime(new Date());// 本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(business.getFirstFollowerId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
        business.setSingleUserId(allotUser.getId());
        business.setSingleOrgId(allotUser.getOrgId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);// 分配
        business.setIsImportant(business.getIsImportant() + 1);// 记录分配次数
        String content = (allotType == 2 ? "自动" : "人工") + "分配商机【" + receiver.getName() + receiver.getLoginName() + "】";
        // 将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        // 写上新增备注，发送短信通知
        // saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT,
        // content, allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
        // 分配是否计算 成本
        // Integer costPrice = iscost(business); //是否计算成本；
        // business.setCostPrice(costPrice);
        if (type == 1) {
            saveUserAllotDeptCount(business.getTypeCode(), receiver.getOrgId(), allotUser);
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ALLOT);// 当前操作为分配
            saveBusinessJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT, content, allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(),
                    business.getFollowerOrganizationId(), business.getFollowerName());
        } else {
            // 多次二次分配以后 再上次分配部门写上被分配人
            if (business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_DEPT)) {
                Query query = repository.getSession().createQuery("From CustomerRecord cus where cus.tableId =" + business.getId() + " and cus.recordType ='"
                        + CustomerRecordConstant.BUS_OPERATE_DEPT + "' order by cus.createTime desc");
                CustomerRecord customerRecord = (CustomerRecord) query.list().get(0);
                customerRecord.setToUserId(receiver.getId());
                saveBusinessAgainRecord(business, customerRecord, receiver); // 修改上次备注被分配人
            }
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DEPT_ALLOT);// 当前操作为部门已分配
            saveBusinessJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_DEPT_ALLOT, content, allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(),
                    business.getFollowerOrganizationId(), business.getFollowerName());

        }

        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(), business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        // 分配累计记录
        saveUserAllotCount(business.getAddTypeCode(), receiver, allotUser);


        // 给客户发短信
        Customer customer = customerService.findCustomerById(business.getCustomerId());
        if ("MB".equals(customer.getContactWay())) {
            String msgContent = "尊敬的客户，您好！感谢您的咨询，稍后会有专业顾问" + receiver.getName() + "给您来电沟通，请注意接听，谢谢！";
            SmsBaiwu.sendMsg(customer.getCustomerPhone(), msgContent);
        }
        try {
           TreeBook book = treeBookService.queryTreeBookByCode(business.getBusinessOrganizationId() + "");
           if (receiver != null && null != book.getExt5() && book.getExt5().trim().equals("open")) { // 成都融资上门
                //	synchronousNotUpdateBusiness(business.getId() + "", allotUser);// 手动同步到小顶上门
              DggMessageSendUtil.putMessage("net.dgg.dggcloud.service.jrcrm.service.mq.doorQueue", business.getId());
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 商机电销分配，并写入分配日志，发送提醒短信给商务
     *
     *
     * @param business  被分配的商机
     * @param receiver  商机接收人
     * @param allotUser 分配人，即当前操作人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotDpBusiness(Business business, User receiver, User allotUser, Integer isdaodian) {
        if (null == business.getBusinessOrganizationId()) {
            throw new BizException("商机未选择受理事业部，无法分配", 10001);
        }
        business.setUpdaterUser(allotUser);// 将分配人写入update数据中，用于在界面展示
        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_FOLLOWING) && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING)
                && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_SIGNED) && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DP_DROP)) {
            throw new BizException("商机已完成分配，不能再次分配!", 10001);
        }
        if (null != business.getOpportunitytypeCode() && !business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_5)) {
            Map numMap = new HashMap();
            numMap.put("followerId", receiver.getId());
            isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(receiver.getOrgId()));
        }
        business.setDistributionTime(new Date());// 本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(receiver.getId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setSingleUserId(allotUser.getId());
        business.setSingleOrgId(allotUser.getOrgId());
        if (null != isdaodian && isdaodian != 1) {
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DAODIAN);// 当前操作分配到店
            // 将分配操作写在最后一次备注上
            business.setLastFollowRecordContent("分配到店");
            business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(receiver.getOrgId()));
        } else {
            //		business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_SHANGMEN);// 当前操作为分配上门
//			business.setBusinessStatus(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING); //上门跟进中
//			business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
            business.setVisitStatus(CustomerRecordConstant.BUS_WAIT_VISIT); //待上门
            // 将分配操作写在最后一次备注上
            business.setLastFollowRecordContent("分配上门");
            business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(receiver.getOrgId()));
            Map<String, String> map = new HashMap<>();
            Customer cus = customerService.findCustomerById(business.getCustomerId());
            map.put("businessCode", business.getNo());
            map.put("customerName", cus.getName()); // 客户名称
            map.put("customerPhone", njCodeUtil.decrypt(cus.getCustomerPhone())); // 客户名称
            // map.put("customerPhone",cus.getCustomerPhoneBak()); //客户名称
            if (null != cus.getSex() && cus.getSex().equals("KHXB_WOMAN")) {
                map.put("customerSex", "2"); // 客户性别
            } else if (null != cus.getSex() && cus.getSex().equals("KHXB_MAN")) {
                map.put("customerSex", "1"); // 客户性别
            } else {
                map.put("customerSex", "0"); // 客户性别
            }
            map.put("message", business.getDescription());// 客户留言
            // map.put("customerPhone","13096323923"); //客户电话
            String city = business.getCity();
            String province = business.getProvince();
            map.put("cityName", city);// 城市名字
            if (StringUtils.isNotEmpty(city)) {
                boolean contains = city.contains("市");
                if (contains && !city.equals("市辖区")) {// 名字里面有 市
                    map.put("cityName", city);// 城市名字
                } else {// 名字里面没有 市

                    if (StringUtils.isNotEmpty(province)) {
                        switch (province) {
                            case "四川省":
                                map.put("cityName", "成都市");// 城市名字
                                break;
                            case "河南省":
                                map.put("cityName", "郑州市");// 城市名字
                                break;
                            case "重庆市":
                                map.put("cityName", "重庆市");// 城市名字
                                break;
                            case "广东省":
                                map.put("cityName", "广州市");// 城市名字
                                break;
                            case "浙江省":
                                map.put("cityName", "杭州市");// 城市名字
                                break;
                            case "北京市":
                                map.put("cityName", "北京市");// 城市名字
                                break;
                            case "湖北省":
                                map.put("cityName", "武汉市");// 城市名字
                                break;
                            case "湖南省":
                                map.put("cityName", "长沙市");// 城市名字
                                break;
                            default:
                                map.put("cityName", "成都市");// 城市名字
                        }
                    }
                }
            } else {
                if (StringUtils.isNotEmpty(province)) {
                    switch (province) {
                        case "四川省":
                            map.put("cityName", "成都市");// 城市名字
                            break;
                        case "河南省":
                            map.put("cityName", "郑州市");// 城市名字
                            break;
                        case "重庆市":
                            map.put("cityName", "重庆市");// 城市名字
                            break;
                        case "广东省":
                            map.put("cityName", "广州市");// 城市名字
                            break;
                        case "浙江省":
                            map.put("cityName", "杭州市");// 城市名字
                            break;
                        case "北京市":
                            map.put("cityName", "北京市");// 城市名字
                            break;
                        case "湖北省":
                            map.put("cityName", "武汉市");// 城市名字
                            break;
                        case "湖南省":
                            map.put("cityName", "长沙市");// 城市名字
                            break;
                        default:
                            map.put("cityName", "成都市");// 城市名字
                    }
                }
            }
            map.put("assignerWorkno", allotUser.getLoginName());// 分配人工号
            User followUser = userService.getUserById(business.getFollowerId());
            map.put("commerceWorkno", followUser.getLoginName());// 商机所属人工号
            map.put("bizCode", "rzsm");// 业态
            map.put("channelCode", "jriboss");// 渠道

//			HttpResult result = null;
//			String url = ConfigLoader.getConfigLoader().getVaule("dx_api_url").trim();
//			try {
//				result = httpCon.PostJson(url.trim(), map);
//			} catch (Exception e) {
//				e.printStackTrace();
//			//	throw new BizException("接口调用失败，请稍后再试!", 10001);
//			}
//			Map mapjson = JsonUtil.json2Obj(result.getData(), Map.class);
//			logger.info("小顶上门接口异常：" + mapjson);
//			if (mapjson.get("code").toString().equals("-2")) {// 返回结果不为0则分配失败
//			//	throw new BizException(mapjson.get("msg").toString(), 10001);
//			}
//			if (mapjson.get("code").toString().equals("-1")) {// 返回结果不为0则分配失败
//			//	throw new BizException("接口调用失败，小顶接口数据异常!", 10001);
//			}
//
//			if (!mapjson.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
//			//	throw new BizException("接口调用失败，请稍后再试!", 10001);
//			}
            // app接口+

            // httpClient.post("","");
        }
//		business.setSingleUserId(allotUser.getId());
//		business.setSingleOrgId(allotUser.getOrgId());
//		business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);//分配
//		business.setIsImportant(business.getIsImportant()+1);//记录分配次数

        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        // 写上新增备注，发送短信通知
        // saveBusinessRecord(business, business.getBusinessOperate(),business,
        // allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
        business.setDxAllotUser(allotUser.getName() + allotUser.getLoginName());
        business.setDxAllotUserId(allotUser.getId());
        saveBusinessFpJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_SHANGMEN, business.getLastFollowRecordContent(), allotUser.getId(), allotUser.getOrgId(),
                business.getFollowerId(), business.getFollowerOrganizationId(), business.getFollowerName());
        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(), business.getNo(), DateUtil.dateToString(business.getDistributionTime()));

        // 分配累计记录
        //saveUserAllotCount(business.getAddTypeCode(), receiver, allotUser);

    }

    /**
     * 小顶上门同步，并写入分配日志，发送提醒短信给商务
     *
     * @param business  被分配的商机
     * @param receiver  商机接收人
     * @param allotUser 分配人，即当前操作人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void synchronousDpBusiness(Business business, User receiver, User allotUser) {
        if (null == business.getBusinessOrganizationId()) {
            throw new BizException("商机未选择受理事业部，无法同步", 10001);
        }
        // business.setUpdaterUser(allotUser);//将分配人写入update数据中，用于在界面展示

//        business.setDistributionTime(new Date());// 本次分配时间
//        business.setFollowerName(receiver.getName() + receiver.getLoginName());
//        business.setFollowerId(receiver.getId());
//        business.setFollowerOrganizationId(receiver.getOrgId());
//        business.setSingleUserId(allotUser.getId());
//        business.setSingleOrgId(allotUser.getOrgId());

//			business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_SHANGMEN);//当前操作为分配上门
//			business.setBusinessStatus(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING); //上门跟进中
//			business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
        // 将分配操作写在最后一次备注上
//        business.setLastFollowRecordContent("待上门");
//        business.setVisitStatus(CustomerRecordConstant.BUS_WAIT_VISIT); // 待上门

        Map<String, String> map = new HashMap<>();
        Customer cus = customerService.findCustomerById(business.getCustomerId());
        map.put("businessCode", business.getNo());
        map.put("customerName", cus.getName()); // 客户名称
        map.put("customerPhone", njCodeUtil.decrypt(cus.getCustomerPhone())); // 客户名称
        // map.put("customerPhone",cus.getCustomerPhoneBak()); //客户名称
        if (null != cus.getSex() && cus.getSex().equals("KHXB_WOMAN")) {
            map.put("customerSex", "2"); // 客户性别
        } else if (null != cus.getSex() && cus.getSex().equals("KHXB_MAN")) {
            map.put("customerSex", "1"); // 客户性别
        } else {
            map.put("customerSex", "0"); // 客户性别
        }
        map.put("message", business.getDescription());// 客户留言
        // map.put("customerPhone","13096323923"); //客户电话
        String city = business.getCity();
        String province = business.getProvince();
        map.put("cityName", city);// 城市名字
        if (StringUtils.isNotEmpty(city)) {
            boolean contains = city.contains("市");
            if (contains && !city.equals("市辖区")) {// 名字里面有 市
                map.put("cityName", city);// 城市名字
            } else {// 名字里面没有 市

                if (StringUtils.isNotEmpty(province)) {
                    switch (province) {
                        case "四川省":
                            map.put("cityName", "成都市");// 城市名字
                            break;
                        case "河南省":
                            map.put("cityName", "郑州市");// 城市名字
                            break;
                        case "重庆市":
                            map.put("cityName", "重庆市");// 城市名字
                            break;
                        case "广东省":
                            map.put("cityName", "广州市");// 城市名字
                            break;
                        case "浙江省":
                            map.put("cityName", "杭州市");// 城市名字
                            break;
                        case "北京市":
                            map.put("cityName", "北京市");// 城市名字
                            break;
                        case "湖北省":
                            map.put("cityName", "武汉市");// 城市名字
                            break;
                        case "湖南省":
                            map.put("cityName", "长沙市");// 城市名字
                            break;
                        default:
                            map.put("cityName", "成都市");// 城市名字
                    }
                }
            }
        } else {
            if (StringUtils.isNotEmpty(province)) {
                switch (province) {
                    case "四川省":
                        map.put("cityName", "成都市");// 城市名字
                        break;
                    case "河南省":
                        map.put("cityName", "郑州市");// 城市名字
                        break;
                    case "重庆市":
                        map.put("cityName", "重庆市");// 城市名字
                        break;
                    case "广东省":
                        map.put("cityName", "广州市");// 城市名字
                        break;
                    case "浙江省":
                        map.put("cityName", "杭州市");// 城市名字
                        break;
                    case "北京市":
                        map.put("cityName", "北京市");// 城市名字
                        break;
                    case "湖北省":
                        map.put("cityName", "武汉市");// 城市名字
                        break;
                    case "湖南省":
                        map.put("cityName", "长沙市");// 城市名字
                        break;
                    default:
                        map.put("cityName", "成都市");// 城市名字
                }
            }
        }
        map.put("assignerWorkno", allotUser.getLoginName());// 分配人工号
        User followUser = userService.getUserById(business.getFollowerId());
        map.put("commerceWorkno", followUser.getLoginName());// 商机所属人工号
        map.put("bizCode", "rzsm");// 业态
        map.put("channelCode", "jriboss");// 渠道

        HttpResult result = null;
        String url = ConfigLoader.getConfigLoader().getVaule("dx_api_url").trim();
        try {
            result = httpCon.PostJson(url.trim(), map);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Map mapjson = JsonUtil.json2Obj(result.getData(), Map.class);
//        logger.info("小顶上门接口异常：" + mapjson);
//        if (mapjson.get("code").toString().equals("-2")) {// 返回结果不为0则分配失败
//            //	throw new BizException(mapjson.get("msg").toString(), 10001);
//        }
//        if (mapjson.get("code").toString().equals("-1")) {// 返回结果不为0则分配失败
//            //	throw new BizException("接口调用失败，小顶接口数据异常!", 10001);
//        }
//
//        if (!mapjson.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
//            //	throw new BizException("接口调用失败，请稍后再试!", 10001);
//        }
        // app接口+

        // httpClient.post("","");
//		business.setSingleUserId(allotUser.getId());
//		business.setSingleOrgId(allotUser.getOrgId());
//		business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);//分配
//		business.setIsImportant(business.getIsImportant()+1);//记录分配次数

//        business.setLastFollowRecordTime(new Date());
//        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        // 写上新增备注，发送短信通知
        // saveBusinessRecord(business, business.getBusinessOperate(),business,
        // allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
//去掉待上门	saveBusinessJsonRecord(business, business.getVisitStatus(), business.getLastFollowRecordContent(), allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(),
//				business.getFollowerOrganizationId(), business.getFollowerName());
        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        // sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(),
        // business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        // 分配累计记录
        // saveUserAllotCount(business.getAddTypeCode(), receiver, allotUser);
    }

    /**
     * 小顶上门同步，并写入分配日志，发送提醒短信给商务 不修改这边商机状态。
     *
     * @param business  被分配的商机
     * @param receiver  商机接收人
     * @param allotUser 分配人，即当前操作人
     *
     */

    /**
     * 商机pk分配，并写入分配日志，发送提醒短信给商务 newbusiness
     *
     * @param business      被分配的商机 ybusiness 原商机
     * @param receiver      商机接收人
     * @param allotUser     分配人，即当前操作人
     * @param customerLevel 客户等级，自动分配时需要传入
     * @param allotType     1人工，2自动 type 1 资源端 2部门
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotPkBusiness(Business business, Business ybusiness, User receiver, User allotUser, String customerLevel, int allotType, int type) {
        if (null == receiver) {// 接收人为空，则调用自动分配的接口
            if (null == business.getBusinessOrganizationId()) {
                throw new BizException("商机未选择受理事业部，无法分配", 10001);
            }
            business.setUpdaterUser(allotUser);// 将分配人写入update数据中，用于在界面展示
            JSONObject map = new JSONObject();
            map.put("opportunityId", business.getId());
            customerLevel = StringUtils.isBlank(customerLevel) ? "0" : customerLevel.trim();
            customerLevel = customerLevel.replace("CUS_KHZZ_STAR_", "");// 等级的格式应该为CUS_KHZZ_STAR_3.5
            BigDecimal lev = new BigDecimal(0);// 默认都是0星资源
            try {
                lev = new BigDecimal(customerLevel);
            } catch (Exception e) {
            }
            map.put("customerLevel", lev.setScale(1, BigDecimal.ROUND_DOWN).doubleValue());
            map.put("businessUnitId", business.getBusinessOrganizationId());
            JSONObject addtionInfo = new JSONObject();
            addtionInfo.put("allotUserId", allotUser.getId());
            map.put("addtionInfo", addtionInfo);
            try {
                String rest = HttpRequest.httpPostWithJSON(ConfigLoader.getConfigLoader().getVaule("autodispatchurl").trim(), map);
                Map result = JsonUtil.json2Obj(rest, Map.class);
                if (!result.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                    throw new BizException("自动分配失败，请稍后再试!", 10001);
                }
            } catch (Exception e) {
                throw new BizException("自动分配请求失败，请提醒管理员检查分配服务!", 10001);
            }
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT);// 将当前操作改为进入分配队列

            return;
        }

        business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(receiver.getId());// 第一次接收人
        business.setFirstFollowerOrganizationId(receiver.getOrgId());// 第一次接收人部门id
        business.setDistributionTime(new Date());// 本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(business.getFirstFollowerId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
        business.setSingleUserId(allotUser.getId());
        business.setSingleOrgId(allotUser.getOrgId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);// 分配
        business.setIsImportant(1);// 记录分配次数

        String content = (allotType == 2 ? "自动" : "人工") + "分配商机";
        // 将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        // 写上新增备注，发送短信通知
        // saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT,
        // content, allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
        // 分配是否计算 成本
//        Integer costPrice = iscost(business); //是否计算成本；
//        business.setCostPrice(costPrice);
        if (type == 1) {
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ALLOT);// 当前操作为分配
            saveBusinessPkJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT, content, allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(),
                    business.getFollowerOrganizationId(), business.getFollowerName());
        } else {
            // 多次二次分配以后 再上次分配部门写上被分配人
            if (business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_DEPT)) {
                Query query = repository.getSession().createQuery("From CustomerRecord cus where cus.tableId =" + business.getId() + " and cus.recordType ='"
                        + CustomerRecordConstant.BUS_OPERATE_DEPT + "' order by cus.createTime desc");
                CustomerRecord customerRecord = (CustomerRecord) query.list().get(0);
                customerRecord.setToUserId(receiver.getId());
                saveBusinessAgainRecord(business, customerRecord, receiver); // 修改上次备注被分配人
            }
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DEPT_ALLOT);// 当前操作为部门已分配
            saveBusinessPkJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_DEPT_ALLOT, content, allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(),
                    business.getFollowerOrganizationId(), business.getFollowerName());
        }
        User u = repository.get(User.class, ybusiness.getFollowerId());
        if (null != u)
            sendBusinessMsg(u, allotUser, "SJ_PK_0001", u.getName(), ybusiness.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(), business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        // 分配累计记录
        saveUserAllotCount(business.getAddTypeCode(), receiver, allotUser);


        // 给客户发短信
        Customer customer = customerService.findCustomerById(business.getCustomerId());
        if ("MB".equals(customer.getContactWay())) {
            String msgContent = "尊敬的客户，您好！感谢您的咨询，稍后会有专业顾问" + receiver.getName() + "给您来电沟通，请注意接听，谢谢！";
            SmsBaiwu.sendMsg(customer.getCustomerPhone(), msgContent);
        }
    }

    /**
     * 商机抢单，并写入分配日志，发送提醒短信给商务
     *
     * @param business 被分配的商机
     * @param receiver 商机接收人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void singBusiness(Business business, User receiver) {
        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT_SING)) {
            throw new BizException("商机已完成抢单，不能再次抢单!", 10001);
        }
        // 多次二次分配以后 再上次分配部门写上被分配人
        if (business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_DEPT)) {
            Query query = repository.getSession().createQuery("From CustomerRecord cus where cus.tableId =" + business.getId() + " and cus.recordType ='"
                    + CustomerRecordConstant.BUS_OPERATE_DEPT + "' order by cus.createTime desc");
            CustomerRecord customerRecord = (CustomerRecord) query.list().get(0);
            customerRecord.setToUserId(receiver.getId());
            saveBusinessAgainRecord(business, customerRecord, receiver); // 修改上次备注被分配人
        }
        business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(receiver.getId());// 第一次接收人
        business.setFirstFollowerOrganizationId(receiver.getOrgId());// 第一次接收人部门id
        business.setDistributionTime(new Date());// 本次分配时间
        business.setFollowerName(receiver.getName() + receiver.getLoginName());
        business.setFollowerId(business.getFirstFollowerId());
        business.setFollowerOrganizationId(receiver.getOrgId());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
        business.setBusinessOperate(CustomerRecordConstant.BUS_SING);// 当前操作为抢单
//		Integer costPrice = iscost(business);//商机是否计算成本；
//		business.setCostPrice(costPrice);
//        business.setSingleUserId(allotUser.getId());
//        business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);//分配

        String content = "抢了商机";

        // 将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(receiver.getName() + receiver.getLoginName());
        // 写上新增备注，发送短信通知
        // saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT,
        // content, allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
        saveBusinessJsonRecord(business, CustomerRecordConstant.BUS_SING, content, business.getFollowerId(), business.getFollowerOrganizationId(), business.getFollowerId(),
                business.getFollowerOrganizationId(), business.getFollowerName());
        sendBusinessMsg(receiver, receiver, "SJ_QD_SUCCESS", business.getNo());
        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        // sendBusinessMsg(receiver, allotUser, "SJ_0001", receiver.getName(),
        // business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        // 分配累计记录
        saveUserAllotCount(business.getAddTypeCode(), receiver, receiver);
        // 给客户发短信
        Customer customer = customerService.findCustomerById(business.getCustomerId());
        if ("MB".equals(customer.getContactWay())) {
            String msgContent = "尊敬的客户，您好！感谢您的咨询，稍后会有专业顾问" + receiver.getName() + "给您来电沟通，请注意接听，谢谢！";
            SmsBaiwu.sendMsg(customer.getCustomerPhone(), msgContent);
        }
    }

    /**
     * 商机分配到部门，并写入分配日志，发送提醒短信给商务经理
     *
     * @param business  被分配的商机
     * @param leader    接收部门领导人
     * @param org       接收部门
     * @param allotUser 分配人
     *                  type  1自动
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void allotBusinessDept(Business business, User leader, OrganizationEntity org, User allotUser,Integer type) {
        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_AUTO_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN)) {
            throw new BizException("商机已完成分配，不能再次分配!", 10001);
        }
        long deptId = org.getId();
        business.setFirstDistributionTime(new Date());
        business.setFirstFollowerId(leader.getId());// 第一次接收人

        business.setFirstFollowerOrganizationId(deptId);// 第一次接收人部门id
        business.setDistributionTime(new Date());// 本次分配时间
        business.setFollowerOrganizationId(deptId);
        business.setFollowerId(leader.getId());
        business.setFollowerName(leader.getName() + leader.getLoginName());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_DEPT);// 部门待分配
        business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);// 部门库
        business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DEPT);// 当前操作为分配到部门
        business.setSingleUserId(allotUser.getId());
        business.setSingleOrgId(allotUser.getOrgId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_1);// 分配
        String msg =type == 1?"自动":"人工";
        String content = msg+"分配商机到部门【" + org.getName() + "】";
        // 将分配操作写在最后一次备注上
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
        business.setIsImportant(business.getIsImportant() + 1);// 记录分配次数
//		Integer costPrice = iscost(business); //是否计算成本；
//		business.setCostPrice(costPrice);
        DeptSet deptSet = deptSetService.getDeptSet(deptId);
        if (null == leader) {
            throw new BizException("该部门领导不存在，不能分配!", 10001);
        }
        if (null != leader && leader.getLocked() != 0) {
            throw new BizException("该部门领导已经离职，不能分配!", 10001);
        }
        if (null != deptSet && deptSet.getIsGrabOrder() == 1) { // 部门开启抢单在个人库
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_DEPT_SING);// 部门待抢单
            business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);// 部门库
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DEPT);// 当前操作为分配到部门
        }
        // 写上新增分配到部门备注，发送短信通知
        // saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ALLOT,
        // content, allotUser.getId(), null, business.getFollowerId(), null,
        // business.getFollowerOrganizationId(), "", business.getFollowerName());
        saveBusinessJsonRecord(business, CustomerRecordConstant.BUS_OPERATE_DEPT, content, allotUser.getId(), allotUser.getOrgId(), business.getFollowerId(), deptId,
                business.getFollowerName());
        // messageService.sendMessage(receiver, allotUser, "您的商机【" + business.getNo() +
        // "】在【" + DateUtil.dateToString(business.getDistributionTime()) +
        // "】分配给你，请你尽快跟进", 3, 2);
        // 发送给经理
        if (business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT))
            sendBusinessMsg(leader, allotUser, "SJ_FP_001", leader.getName(), business.getNo());
        if (business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT_SING)) {
            Map map = new HashMap();
            map.put("locked", 0);
            map.put("orgId", business.getFollowerOrganizationId()); //部门
            map.put("rootOrgId", null == business.getFollowerOrganizationId() ? -1L : business.getFollowerOrganizationId());
            // 获取当前部门所在用户
            map.put("deptId", getUserOrganizationIds(business.getFollowerOrganizationId()));
//        userMap.put("userRole","5");//5代表的是商务顾问
            map.put("userRoleCodes", "bus_advisor");
            map.put("userReceive", "1"); //是否接单
            map.put("monthNum", "0");// 月接单量不能小于的数字
//      Integer count = userService.searchUserCount(userMap);
            PageData<Map> data = userService.searchUser(map);
            List<Map> userMap = data.getData();
            User newUser = new User();
            sendBusinessMsg(leader, allotUser, "SJ_QD_0001", business.getNo());
            for (Map u : userMap) {
                if (!u.get("userid").equals(leader.getId())) {
                    newUser.setId(Long.parseLong(u.get("userid") + ""));
                    newUser.setPhone(u.get("phone").toString());
                    sendBusinessMsg(newUser, allotUser, "SJ_QD_0001", business.getNo());
                }
            }
        }

        // 分配累计记录
        saveUserAllotDeptCount(business.getTypeCode(), deptId, allotUser);

    }

    /**
     * 商机自动分配完成后，回调该方法
     *
     * @param businessId  商机id
     * @param userId      接收用户id
     * @param allotUserId 分配人id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveAutoAllotBusiness(Long businessId, Long userId, Long allotUserId, String type) throws Exception {
        if (null == businessId) {
            throw new BizException("商机不存在", 10001);
        }
        // TODO: 2018-12-07
        //Business business = repository.get(Business.class, businessId);

        Map autoMap = new HashMap();
        autoMap.put("busId",Long.valueOf(businessId));
        Business business = getMinDaoBisiness(businessId);
        if (null == business) {
            throw new BizException("商机不存在", 10001);
        }

        if (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_AUTO_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT)) {
            throw new BizException("商机状态已更新，不能再次分配", 10201);
        }
        User allotUser = repository.get(User.class, allotUserId);
        if (null == allotUser) {
            throw new BizException("商机分配人不存在", 10001);
        }
        if (null == userId) {
            throw new BizException("商机接收人或部门不存在", 10001);
        }
        User rUser = null;
        if (type.equals("dept")) {
            OrganizationEntity org = organizationService.find4Id(userId);
            rUser = repository.get(User.class, org.getLeaderId());
            allotBusinessDept(business, rUser, org, allotUser,1);// 分配到部门
        } else {

            if (null == userId) {// 接收人id为空，代表当前没有找到可接商机的商务，应提示创建人和分配人
                User creater = repository.get(User.class, business.getCreaterId());
                User sysUser = repository.get(User.class, 1L);
                sendBusinessMsg(allotUser, sysUser, "SJ_0005", business.getNo());
                if (allotUser.getId().longValue() != creater.getId().longValue()) {// 分配人和新建人不是同一个人
                    sendBusinessMsg(creater, sysUser, "SJ_0005", business.getNo());
                }

                return;
            }
            rUser=repository.get(User.class, userId);
            if (null == rUser) {
                throw new BizException("商机接收人不存在", 10001);
            }
            allotBusiness(business, rUser, allotUser, "", 2, 1);
        }
        setBusinessWillDropDate(business);
        repository.saveOrUpdate(business);

    }

    /**
     * 保存分配记录
     *
     * @param addTypeCode 资源端分配类型
     * @param receiver    接收人
     * @param allotUser   分配人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveUserAllotCount(String addTypeCode, User receiver, User allotUser) {
        Integer month = Integer.valueOf(DateUtil.dateToString(new Date(), "yyyyMM"));
        BusinessAllotCount oldBac = businessAllotCountService.getUserAllotCount(receiver.getId(), receiver.getOrgId(), addTypeCode, month);
        if (null == oldBac) {
            BusinessAllotCount bac = new BusinessAllotCount();
            bac.setCreateUser(allotUser);
            bac.setUserId(receiver.getId());
            bac.setUserOrganizationId(receiver.getOrgId());
            bac.setAllotType(addTypeCode);
            bac.setAllotMonth(month);
            bac.setId(keyWorker.nextId());
            bac.setAllotNumber(1);
            repository.save(bac);
        } else {
            oldBac.setAllotNumber(oldBac.getAllotNumber() + 1);
            repository.saveOrUpdate(oldBac);
        }
        // 接单量小于阀值时发送预警消息
        TreeBook tb = treeBookService.queryTreeBookByCode("JDLYJ");
        if (null != tb && StringUtils.isNotBlank(tb.getExt1())) {
            try {
                Integer value = Integer.valueOf(tb.getExt1());
                UserSetting us = repository.get(UserSetting.class, receiver.getId());
                // 判断月接单量
                List<Map> counts = businessAllotCountService.searchUserAllotRecord(receiver.getId(), DateUtil.dateToString(new Date(), "yyyyMM"));
                if (null != counts && !counts.isEmpty()) {
                    Integer all = 0;
                    for (Map count : counts) {
                        all += Integer.valueOf(count.get("allotnumber").toString());
                    }
                    if ((us.getMonthNum() - all) <= value) {
                        sendBusinessMsg(receiver, allotUser, "SJ_0017", receiver.getName() + receiver.getLoginName(), tb.getExt1());
                    }
                }

            } catch (Exception e) {
                logger.error("发送接单量预警消息出现异常：" + e.getMessage());
            }
        }
        // 记录商务今日已分配的累计量
        CacheManager.getOperator().incr(CommonConstant.ORGANIZATION_KEY + DateUtil.dateToString(new Date(), "yyyyMMdd") + ":" + receiver.getId().toString());
    }

    /**
     * 保存分配记录
     *
     * @param addTypeCode 资源端分配类型
     * @param allotUser   分配人
     */
    @Transactional(propagation = Propagation.REQUIRED)
    private void saveUserAllotDeptCount(String addTypeCode, Long deptId, User allotUser) {
        Integer month = Integer.valueOf(DateUtil.dateToString(new Date(), "yyyyMM"));
        BusinessAllotDeptCount oldBac = businessAllotDeptCountService.getUserAllotCount(deptId, addTypeCode, month);
        if (null == oldBac) {
            BusinessAllotDeptCount bac = new BusinessAllotDeptCount();
            bac.setCreateUser(allotUser);
            bac.setOrganizationId(deptId);
            bac.setAllotType(addTypeCode);
            bac.setAllotMonth(month);
            bac.setId(keyWorker.nextId());
            bac.setAllotNumber(1);
            repository.save(bac);
        } else {
            oldBac.setAllotNumber(oldBac.getAllotNumber() + 1);
            repository.saveOrUpdate(oldBac);
        }
        // 记录商务今日已分配的累计量
        CacheManager.getOperator().incr(CommonConstant.ORGANIZATION_KEY + DateUtil.dateToString(new Date(), "yyyyMMdd") + ":" + deptId.toString());
    }

    /**
     * 商机详情页面修改商机信息
     *
     * @param business 商机修改后的信息
     * @param reqParam 页面参数
     */
    public void updateBusinessInfo(Business business, Map reqParam) {
        Business oldInfo = repository.get(Business.class, business.getId());
        if (null == oldInfo) {
            throw new BizException("商机信息不能为空", 10001);
        }
        User user = (User) reqParam.get("user");

        if (null == oldInfo.getFollowerId() && oldInfo.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_SOURCE.intValue()) {
            throw new BizException("商机状态已更新，当前人无权修改信息", 10001);
        }

        if (null != oldInfo.getFollowerId() && user.getId().longValue() != oldInfo.getFollowerId().longValue()) {
            throw new BizException("用户无权修改商机信息", 10001);
        }

        if (null != business.getIsVip() && business.getIsVip() == 1) {// 判断VIP容量
            oldInfo.setVipTime(new Date());
            UserSetting us = repository.get(UserSetting.class, user.getId());
            if (null == us || null == us.getVipNum()) {
                throw new BizException("用户VIP容量未设置，无法设置vip", 10001);
            }
            Map vipParam = new HashMap();
            vipParam.put("followerId", user.getId().toString());
            vipParam.put("isVip", "1");
            vipParam.put("idNotIn", business.getId().toString());
            Integer vipCount = businessDao.countBusinessByMap(vipParam);
            Map map = new HashMap();
            map.put("type", 1);
            map.put("id", user.getId());
            Integer fb = vipCountService.countVipListByParams(map);// 分配的VIP
            fb = NumberUtils.toInt(fb + "");
            map.put("type", 2);
            Integer sh = vipCountService.countVipListByParams(map);// 收回的VIP
            sh = NumberUtils.toInt(sh + "");
            if (vipCount >= (us.getVipNum().intValue() + fb - sh)) {
                throw new BizException("用户VIP容量超出限制，无法设置vip", 10001);
            }
        }
        oldInfo.setIsVip(business.getIsVip());
        oldInfo.setCustomerName(business.getCustomerName());
        oldInfo.setLoanAmount(business.getLoanAmount());
        oldInfo.setLoanTime(business.getLoanTime());
        oldInfo.setLoanCycle(business.getLoanCycle());
        oldInfo.setLoanInterrestRate(business.getLoanInterrestRate());
        oldInfo.setLoadInterrestValue(business.getLoadInterrestValue());
        oldInfo.setRepaymentType(business.getRepaymentType());
        oldInfo.setSpecialRemark(business.getSpecialRemark());
        oldInfo.setUpdaterUser(user);
        setBusinessWillDropDate(oldInfo);
        setBusinessWillLzDate(oldInfo);
        reqParam.put("User", user);
        reqParam.put("id", oldInfo.getCustomerId());
        reqParam.put("name", oldInfo.getCustomerName());
        // 客户评分使用
        reqParam.put("business", oldInfo);
        Customer customer = customerApiService.updateCustomer(reqParam);
        if (customer.getCustomerAttrFlag() == null || customer.getCustomerAttrFlag().equals("")) {
            customerApiService.saveCustomerAttr(customer, user, business);// 带客户属性
        }
        oldInfo.setCustomerAttr(customer.getCustomerAttrFlag());
        repository.saveOrUpdate(oldInfo);
        saveBusinessRecord(oldInfo, CustomerRecordConstant.BUS_OPERATE_EDIT, "修改商机信息", user.getId(), null, null);
    }

    /**
     * 获取商机已选中的产品id集合，以,号分割
     *
     * @param id 商机id
     * @return
     */
    public String getBusinessSelectedProductIds(Long id) {
        Map map = new HashMap();
        map.put("businessId", id);
        List<Map> ids = businessDao.listBusinessProductByMap(map);
        if (null != ids && !ids.isEmpty()) {
            StringBuffer idArr = new StringBuffer();
            for (int i = 0; i < ids.size(); i++) {
                Map o = ids.get(i);
                idArr.append(o.get("pid"));
                if (i < ids.size() - 1) {
                    idArr.append(",");
                }
            }
            return idArr.toString();
        }
        return "";
    }

    /**
     * 保存商机选择的产品信息
     *
     * @param businessId 商机id
     * @param ids        产品集合
     * @param user       操作人
     */
    public void saveBusProducts(Long businessId, String ids, User user) {
        Business oldInfo = repository.get(Business.class, businessId);
        if (null == oldInfo) {
            throw new BizException("商机信息不能为空", 10001);
        }
//        if (null == oldInfo.getFollowerId() || oldInfo.getFollowerId().longValue() != user.getId().longValue()) {
//            throw new BizException("用户无权修改商机信息", 10001);
//        }
//        //先删除已有的产品信息
//        Map map = new HashMap();
//        map.put("businessId", businessId);
//        businessDao.deleteBusinessProductByMap(map);

        // 再添加新的信息
        if (StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            Map newInfo = new HashMap();
            newInfo.put("businessId", businessId);
            for (String s : idArr) {
                newInfo.put("productId", s);
                businessDao.addBusinessProductByMap(newInfo);
            }
        }
    }

    /**
     * 新增商机备注
     *
     * @param businessId       商机id
     * @param requestParamMap  页面传入的参数
     * @param currentLoginUser 当前操作人
     */
    public void saveBusRemark(Long businessId, Map<String, Object> requestParamMap, User currentLoginUser) {

        if (null == businessId) {
            throw new BizException("商机id信息不能为空", 10001);
        }
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机信息不存在", 10001);
        }
        if (business.getCustomerId() != null) {
            Customer customer = repository.get(Customer.class, business.getCustomerId());
            if (null != customer && (customer.getCustomerAttrFlag() == null || customer.getCustomerAttrFlag().equals(""))) { // 带客户属性过来
                customerApiService.saveCustomerAttr(customer, currentLoginUser, business);
            }
        }
        String remarkStage = null == requestParamMap.get("remarkStage") ? "" : requestParamMap.get("remarkStage").toString().trim();// 跟进阶段
        String remarkContent = null == requestParamMap.get("remarkContent") ? "" : requestParamMap.get("remarkContent").toString().trim();// 跟进内容

        if (StringUtils.isBlank(remarkContent)) {
            throw new BizException("备注内容不能为空", 10001);
        }
        String nextStage = null == requestParamMap.get("nextStage") ? "" : requestParamMap.get("nextStage").toString().trim();// 下次跟进阶段
        String nextFollowTime = null == requestParamMap.get("nextFollowTime") ? "" : requestParamMap.get("nextFollowTime").toString().trim();// 下次跟进时间
        String nextFollowContent = null == requestParamMap.get("nextFollowContent") ? "" : requestParamMap.get("nextFollowContent").toString().trim();// 下次跟进内容
        // 判断是否商机当前跟进人在备注,库为个人库
        if (null != business.getFollowerId() && currentLoginUser.getId().longValue() == business.getFollowerId().longValue()
                && business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EMP.intValue()) {
            if (StringUtils.isBlank(remarkStage)) {
                throw new BizException("跟进阶段不能为空", 10001);
            }
            // 判断商机当前的下一次跟进时间是否小于当前时间，是的话就把下次跟进的内容都置空
            if (null != business.getNextFollowTime() && DateUtil.timeBetween(business.getNextFollowTime(), new Date(), "min") > 0) {
                business.setNextFollowContent(null);
                business.setNextFollowTime(null);
                business.setNextFollowStage("");
            }
            if (StringUtils.isNotBlank(nextFollowTime)) {// 选了下次备注时间
//                if (StringUtils.isBlank(nextStage)) {
//                    throw new BizException("下次跟进阶段不能为空", 10001);
//                }
                if (DateUtil.timeBetween(new Date(), DateUtil.stringDateToDate(nextFollowTime, "yyyy-MM-dd HH:mm"), "min") < 1) {
                    throw new BizException("下次跟进时间不能小于当前时间", 10001);
                }
                if (nextFollowContent.length() > 100) {
                    throw new BizException("下次跟进内容不能超过100字符", 10001);
                }
                business.setNextFollowContent(nextFollowContent);
                business.setNextFollowStage(nextStage);
                business.setNextFollowTime(DateUtil.stringDateToDate(nextFollowTime, "yyyy-MM-dd HH:mm"));
            }
            // 更新商机的当前操作
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_FOLLOW);
            business.setLastFollowTime(new Date());
            business.setBusinessStage(remarkStage);

            // 判断商机是否是待跟进，是的话改为跟进中
            if (business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
            }
            // 判断商机第一次跟进时间是否为空，是的话该为当前时间
            if (null == business.getFirstFollowTime()) {
                business.setFirstFollowTime(new Date());
            }
            // 商机跟进次数+1，计算最近的掉库时间
            Integer times = business.getFollowTimes() == null ? 1 : business.getFollowTimes() + 1;
            business.setFollowTimes(times);
            business.setUpdaterUser(currentLoginUser);
            setBusinessWillDropDate(business);
            setBusinessWillLzDate(business);// 商机预计流转时间

            // 设置分组
            String _groupId = null == requestParamMap.get("groupId") ? null : requestParamMap.get("groupId").toString().trim();// groupId
            Long groupId = StringUtils.isEmpty(_groupId) ? null : Long.valueOf(_groupId);
            business.setGroupId(groupId);

        }
        // 更新最后一次备注信息
        business.setLastFollowRecordContent(remarkContent);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
        String fileId = null == requestParamMap.get("remarkFileId") ? "" : requestParamMap.get("remarkFileId").toString().trim();// 下次跟进时间
        // 写入备注内容
        saveBusinessFileRecord(business, CustomerRecordConstant.BUS_OPERATE_FOLLOW, remarkContent, currentLoginUser.getId(), business.getFollowerId(), null,
                business.getFollowerOrganizationId(), null, "", "", fileId);
        repository.saveOrUpdate(business);
    }

    /**
     * 提醒商务、商务经理
     *
     * @param businessId 商机id
     * @param type       提醒类型，1商务，2经理
     * @param user       提醒人
     */
    public void saveRemindBusinessFollower(Long businessId, Integer type, User user) {
        if (null == businessId) {
            throw new BizException("商机id信息不能为空", 10001);
        }
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机信息不存在", 10001);
        }
        // 商机不在个人库就不提醒了
        if (!business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_EMP)) {
            throw new BizException("商机当前无跟进商务", 10001);
        }
        if (type == 2) {
            BizExceptionUtil.isException(null == business.getFollowerOrganizationId(), "商机没有当前跟进部门，无法进行提醒");
            // 查找经理
            Map userMap = new HashMap();
            userMap.put("rootOrgId", business.getFollowerOrganizationId());
//            userMap.put("userRole", "7");//7代表商务经理
            userMap.put("userRoleCodes", "shangwujingli");
            PageData<Map> leaders = userService.searchUser(userMap);
            if (null != leaders && null != leaders.getData() && !leaders.getData().isEmpty()) {
                sendBusinessMsg(repository.get(User.class, Long.valueOf(leaders.getData().get(0).get("userid").toString())), user, "SJ_0007", business.getNo(),
                        business.getCustomerName(), business.getCustomerNo(), business.getFollowerName());
            } else {
                throw new BizException("商机所在部门无商务经理，无法提醒", 10001);
            }
        } else {
            User follower = repository.get(User.class, business.getFollowerId());
            if (null == follower || 0 != follower.getLocked()) {
                throw new BizException("商机跟进商务不存在或不可用，无法提醒", 10001);
            }
            sendBusinessMsg(repository.get(User.class, business.getFollowerId()), user, "SJ_0008", business.getNo(), business.getCustomerName(), business.getCustomerNo());
        }
        // 插入一条二次咨询的备注记录，用于工作台统计二次咨询的商机
        saveBusinessRecord(business, CustomerRecordConstant.REMIND_FOLLOWER, "客户二次咨询", user.getId(), business.getFollowerId(), null, business.getFollowerOrganizationId(), null, "",
                "");

    }

    /**
     * 详情页面添加客户联系人
     *
     * @param contactMap 联系人信息
     * @param businessId 商机id
     * @param user       操作用户
     */
    public void saveCusContact(Map contactMap, Long businessId, User user) {
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机信息不存在", 10001);
        }
        if (null != business.getFollowerId() && user.getId().longValue() != business.getFollowerId().longValue()) {
            throw new BizException("用户无权修改商机信息", 10001);
        }
        contactMap.put("number", njCodeUtil.encrypt(contactMap.get("number").toString()));
        contactMap.put("customerId", business.getCustomerId());
        contactMap.put("User", user);
        contactApiService.saveContact(contactMap);

    }

    /**
     * 设置商机的客户联系人
     *
     * @param businessId 商机id
     * @param contactId  联系人id
     * @param user       操作用户
     * @param type       操作类型 1设置主联系人，2作废联系人，3恢复联系人
     */
    public void updateCusContact(Long businessId, Long contactId, User user, Integer type) {
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机信息不存在", 10001);
        }
        if (null != business.getFollowerId() && user.getId().longValue() != business.getFollowerId().longValue()) {
            throw new BizException("用户无权修改商机信息", 10001);
        }
        Contact contact = repository.get(Contact.class, contactId);
        if (contact.getCustomerId().longValue() != business.getCustomerId().longValue()) {
            throw new BizException("用户无权修改联系人信息", 10001);
        }
        Map map = new HashMap();
        map.put("contactId", contact.getId());
        map.put("customerId", business.getCustomerId());
        map.put("User", user);
        if (type == 1) {
            contactApiService.setMainContact(map);
        } else {
            String status = "CUS_CONT_STATUS_1";
            if (type == 2) {
                status = "CUS_CONT_STATUS_0";
            }
            map.put("status", status);
            contactApiService.updateContactStatus(map);
        }
    }

    /**
     * 手动分配商机,在分配中列表可对商机进行强制的再次分配
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     * @param userId           如果该id为空，则将商机自动分配
     * @param force            是否对已进入分配队列的商机进行1强制分配 2 部门分配
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateManualAllotBusiness(String businessIds, User currentLoginUser, Long userId, Integer force) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_ALLOT_REDIS_INC_KEY + id) > 1) {
                throw new BizException("商机正在分配,请勿重复操作", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_ALLOT_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "alotting...");
            // TODO: 2018-12-07 商机查询主库
            //Business business = getBusinessById(Long.valueOf(id));
//            Map autoMap = new HashMap();
//            autoMap.put("busId",Long.valueOf(id));
            Business business = getMinDaoBisiness(Long.valueOf(id));
            force = null == force ? 0 : force;
            if (2 == force) {
                if (null == business || !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT)
                        || business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_ORG.intValue()) {
                    throw new BizException("商机不存在或已被分配", 10001);
                }
            } else {
                if (null == business
                        || (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN))
                        || business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_SOURCE.intValue()) {
                    throw new BizException("商机不存在或已被分配", 10001);
                }
            }
            if (CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT.equals(business.getBusinessOperate()) && 1 != force) {
                throw new BizException("商机已进入自动分配队列，请耐心等待!", 10001);
            }
            User ruser = null;
            String cLevel = "";
            if (null != userId) {
                ruser = repository.get(User.class, userId);
                // 判断是否可以接单
                isUserCanReceiveBusiness(ruser, currentLoginUser);
                // 判断库容量是否已经满了，满了则不能接单 转介绍除外
                if (null != business.getOpportunitytypeCode() && !business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_5)) {
                    Map numMap = new HashMap();
                    numMap.put("followerId", ruser.getId());
                    isMoreThanSybNum(numMap, business.getBusinessOrganizationId());
                }

            } else {// 自动分配时需要获取商机客户的等级
                Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                cLevel = customer.getLevel();
            }
            if (force == 2) {
                allotBusiness(business, ruser, currentLoginUser, cLevel, 1, 2);
            } else {
                allotBusiness(business, ruser, currentLoginUser, cLevel, 1, 1);
            }
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
//			//如果接收人是小顶上门商务资源直接到APP
//			if(ruser!=null) {
//				if (roleService.userHasRole(ruser, "dianxiaozhuanyuan")) {
//					synchronousWaitBusiness(business.getId() + "", currentLoginUser);//手动同步到小顶上门
//				}
//			}
        }

    }

    /**
     * 电销分配
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     * @param userId           如果该id为空，则将商机自动分配 是否对已进入分配队列的商机进行1强制分配 2 部门分配
     */
    public void updateManualAllotDpBusiness(String businessIds, User currentLoginUser, Long userId, Integer isdaodian) {
        String[] ids = businessIds.split(",");

        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_ALLOT_REDIS_INC_KEY + id) > 1) {
                throw new BizException("商机正在分配,请勿重复操作", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_ALLOT_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "alotting...");
          //  Business business = getBusinessById(Long.valueOf(id));
//            Map autoMap = new HashMap();
//            autoMap.put("busId",Long.valueOf(id));
            Business business = getMinDaoBisiness(Long.valueOf(id));
//			if (null == business || business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING)  ||  business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EP.intValue() ) {
////					throw new BizException("商机不存在或已被分配", 10001);
////				}
            User ruser = null;

            if (null != userId) {
                ruser = repository.get(User.class, userId);
            }
            allotDpBusiness(business, ruser, currentLoginUser, isdaodian);
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 手动同步商机到小顶上门
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     */
    public void synchronousBusiness(String businessIds, User currentLoginUser) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_ALLOT_REDIS_INC_KEY + id) > 1) {
                throw new BizException("商机正在分配,请勿重复操作", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_ALLOT_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "alotting...");
            Business business = getBusinessById(Long.valueOf(id));
            if (null == business
                    || (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)
                    && !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_FOLLOWING))
                    || business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EMP.intValue()) {
                throw new BizException("商机状态不对或已经不属于你，不能同步到小顶上门。", 10001);
            }

            User fuser = null;// 分配人
            User ruser = null;// 接收人
            ruser = repository.get(User.class, business.getFollowerId());
            if (null != business.getSingleUserId()) {// 商机分单人
                fuser = repository.get(User.class, business.getSingleUserId());
                synchronousDpBusiness(business, ruser, fuser);
            } else {
                synchronousDpBusiness(business, ruser, ruser); // 没有分配人 分配人为自己
            }
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 手动同步商机到小顶上门(资源端用)
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户 是否对已进入分配队列的商机进行1强制分配 2 部门分配
     */
    public void synchronousWaitBusiness(String businessIds, User currentLoginUser) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
//			if (null == business || business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING)  ||  business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EP.intValue() ) {
////					throw new BizException("商机不存在或已被分配", 10001);
////				}
            User fuser = null;// 分配人
            User ruser = null;// 接收人
            ruser = repository.get(User.class, business.getFollowerId());
            if (null != business.getSingleUserId()) {// 商机分单人
                fuser = repository.get(User.class, business.getSingleUserId());
                synchronousDpBusiness(business, ruser, fuser);
            } else {
                synchronousDpBusiness(business, ruser, ruser); // 没有分配人 分配人为自己
            }
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 手动同步商机到小顶上门(资源端用)
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户 是否对已进入分配队列的商机进行1强制分配 2 部门分配
     */
    public void synchronousNotUpdateBusiness(String businessIds, User currentLoginUser) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
//			if (null == business || business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING)  ||  business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EP.intValue() ) {
////					throw new BizException("商机不存在或已被分配", 10001);
////				}
            User fuser = null;// 分配人
            User ruser = null;// 接收人
            ruser = repository.get(User.class, business.getFollowerId());
            if (null != business.getSingleUserId()) {// 商机分单人
                fuser = repository.get(User.class, business.getSingleUserId());
                synchronousDpBusiness(business, ruser, fuser);
            } else {
                synchronousDpBusiness(business, ruser, ruser); // 没有分配人 分配人为自己
            }
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }

    }


    /**
     * 手动同步商机到小顶上门(资源端用)
     *
     * @param businessIds 商机id集合
     * @param
     */
    public void mqSynchronousNotUpdateBusiness(String businessIds) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
//			if (null == business || business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DOOR_FOLLOWING)  ||  business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EP.intValue() ) {
////					throw new BizException("商机不存在或已被分配", 10001);
////				}
            User fuser = null;// 分配人
            User ruser = null;// 接收人
            ruser = repository.get(User.class, business.getFollowerId());
            if (null != business.getSingleUserId()) {// 商机分单人
                fuser = repository.get(User.class, business.getSingleUserId());
                synchronousDpBusiness(business, ruser, fuser);
            } else {
                synchronousDpBusiness(business, ruser, ruser); // 没有分配人 分配人为自己
            }
            //setBusinessWillDropDate(business);
            //business.setUpdaterUser(currentLoginUser);
         //   repository.saveOrUpdate(business);
        }

    }

    /**
     * 商机PK分配
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     * @param userId           如果该id为空，则将商机自动分配
     * @param force            是否对已进入分配队列的商机进行1强制分配
     */
    public void updateManualAllotPkBusiness(String businessIds, User currentLoginUser, Long userId, Integer force) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_ALLOT_REDIS_INC_KEY + id) > 1) {
                throw new BizException("商机正在分配,请勿重复操作", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_ALLOT_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "alotting...");
            Business newbusiness = getBusinessById(Long.valueOf(id));

            String json = JsonUtil.obj2Json(newbusiness);
            Business business = new Business();
            business = JsonUtil.json2Obj(json, Business.class);
            business = newBusiness(business);
            // business = newbusiness;
            if (null != newbusiness.getIsPk() && newbusiness.getIsPk() == 1) {
                throw new BizException("商机正在PK，不能再分配", 10001);
            } else {
                User isuser = repository.get(User.class, userId);
                if (newbusiness.getFollowerOrganizationId() == isuser.getOrgId()) {
                    throw new BizException("同一部门的商务不能PK", 10001);
                }
                // 计算商机成本分摊比列
                TreeBook tb = treeBookService.queryTreeBookByCode("BUS_PK_CB");
                int ycb = 0;
                int xcb = 0;
                DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
                if (null != tb && tb.getExt1() != null) {
                    String cb[] = tb.getExt1().split(":");
                    for (int i = 0; i < cb.length; i++) {
                        ycb = NumberUtils.toInt(cb[i]); // 原成本
                        xcb = NumberUtils.toInt(cb[i]); // 现成本
                    }
                    float ynum = (float) ycb / (ycb + xcb); // 原成本所占比列
                    float xnum = (float) 1 - ynum; // 现成本所占比列
                    // 查询当前跟进人的成本
                    Query query = repository.getSession()
                            .createQuery("From CustomerRecord cus where cus.tableId =" + newbusiness.getId() + " and cus.recordType in ('"
                                    + CustomerRecordConstant.BUS_OPERATE_DEPT_ALLOT + "','" + CustomerRecordConstant.BUS_SING + "','" + CustomerRecordConstant.BUS_OPERATE_ALLOT
                                    + "','" + CustomerRecordConstant.BUS_OPERATE_ALLOT_TWO + "') and toUserId =" + newbusiness.getFollowerId() + " order by cus.createTime desc");
                    CustomerRecord Record = (CustomerRecord) query.list().get(0); // 最新成本记录
                    float yext5 = Float.parseFloat(Record.getExt5());
                    Record.setExt5(df.format(Float.parseFloat(Record.getExt5()) * ynum));
                    repository.saveOrUpdate(Record); // 更新原成本
                    float xext5 = yext5 * xnum;
                    business.setPrice(xext5);
                }

                if (newbusiness.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EMP
                        && (newbusiness.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)
                        || newbusiness.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_FOLLOWING))) {
                    // 商机在待跟进 和跟进中 且在个人库 才能进行pk 分配
                    String no = billNumberService.updateBillNumberByCode("SJ");// 商机单据号
                    business.setIsPk(1);
                    business.setNo(no);
                    business.setId(keyWorker.nextId());
                    business.setUpdaterUser(null);
                    business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW); // 待跟进
                    // business
                } else {
                    throw new BizException("商机不在待跟进或跟进中", 10001);
                }
            }
            force = null == force ? 0 : force;
            User ruser = null;
            String cLevel = "";
            if (null != userId) {
                ruser = repository.get(User.class, userId);
                // 判断是否可以接单
                isUserCanReceiveBusiness(ruser, currentLoginUser);

            } else {// 自动分配时需要获取商机客户的等级
                Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                cLevel = customer.getLevel();
            }
            allotPkBusiness(business, newbusiness, ruser, currentLoginUser, cLevel, 1, 1);
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.save(business);
            newbusiness.setIsPk(1);
            repository.saveOrUpdate(newbusiness);
        }

    }

    /**
     * 给pk商机赋值
     *
     * @param b
     * @return
     */
    private Business newBusiness(Business b) {
        b.setUpdaterId(null);
        b.setUpdateTime(null);
        b.setVipTime(null);
        b.setIsVip(0);
        b.setUpdaterId(null);
        b.setUpdaterName(null);
        b.setUpdaterOrgId(null);
        b.setFollowerName(null);

        b.setFirstFollowerId(null);
        b.setFirstFollowerOrganizationId(null);
        b.setFirstFollowTime(null);
        b.setFirstCallTime(null);
        b.setFirstDistributionTime(null);
        b.setFollowerId(null);
        b.setFollowerName(null);
        b.setBusinessStage(null);
        b.setCustomerAttr(null);
        b.setNextFollowTime(null);
        b.setNextFollowStage(null);
        b.setNextFollowContent(null);
        b.setGroupId(null);
        b.setLastFollowRecordContent(null);
        b.setLastFollowRecordTime(null);
        b.setLastFollowRecordUser(null);
        b.setLastFollowTime(null);
        b.setLastReturnVisitTime(null);
        b.setCreateTime(new Date());

        return b;
    }

    /**
     * 手动抢商机
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateManualSingBusiness(String businessIds, User currentLoginUser) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_GRAB_REDIS_INC_KEY + id) > 1) {
                throw new BizException("你来迟了，商机已经被抢了", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_GRAB_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "grabing...");
         //   Business business = getBusinessById(Long.valueOf(id));
            // TODO: 2018-12-07  查主库修改商机状态
//            Map singMap = new HashMap();
//            singMap.put("busId",Long.valueOf(id));
            Business business = getMinDaoBisiness(Long.valueOf(id));
            if (null == business || !business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_DEPT_SING)
                    || business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_ORG.intValue()) {
                throw new BizException("商机不存在或已被抢", 10001);
            }
            // 判断是否可以接单
            isUserCanReceiveBusiness(currentLoginUser);
            // 判断库容量是否已经满了，满了则不能接单
            Map numMap = new HashMap();
            numMap.put("followerId", currentLoginUser.getId());
            isMoreThanSybNum(numMap, business.getBusinessOrganizationId());
            singBusiness(business, currentLoginUser);
            setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 手动分配商机到部门,在分配中列表可对商机进行强制的再次分配
     *
     * @param businessIds      商机id集合
     * @param currentLoginUser 当前操作用户
     * @param deptId           如果该id为空，则将商机自动分配
     * @param force            是否对已进入分配队列的商机进行强制分配
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateManualAllotBusinessDept(String businessIds, User currentLoginUser, Long deptId, Integer force) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            if (CacheManager.getOperator().incr(BusinessConstant.BUSINESS_ALLOT_REDIS_INC_KEY + id) > 1) {
                throw new BizException("商机正在分配,请勿重复操作", 20666);
            }
            CacheManager.getOperator().put(String.format(BusinessConstant.BUSINESS_ALLOT_REDIS_USER_BUSINESS_KEY, currentLoginUser.getId(), id), "alotting...");
            // TODO: 2018-12-07
            //Business business = getBusinessById(Long.valueOf(id));
//            Map autoMap = new HashMap();
//            autoMap.put("busId",Long.valueOf(id));
            Business business = getMinDaoBisiness(Long.valueOf(id));
            if (null == business
                    || (!business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !business.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN))
                    || business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_SOURCE.intValue()) {
                throw new BizException("商机不存在或已被分配", 10001);
            }
            if (business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT) && 1 != force) {
                throw new BizException("商机已进入自动分配队列，请耐心等待!", 10001);
            }
            User ruser = null;
            String cLevel = "";
            DeptSet deptSet = null;
            if (null != deptId) {
                // 判断是否可以接单
                deptSet = deptSetService.getDeptSet(deptId);
                if (deptSet == null) {
                    deptSetService.saveOrUpdateDeptSet(1, 0, deptId);
                    throw new BizException("该部门经理未开启接单，不能分配给该部门!", 10001);
                } else {
                    if (deptSet.getIsOrder() != 1) {
                        throw new BizException("该部门经理未开启接单，不能分配给该部门!", 10001);
                    }

                }
            } else {//
                throw new BizException("部门不存在不能分配!", 10001);
            }
            // 分配到部门
            OrganizationEntity org = repository.get(OrganizationEntity.class, deptId);
            if (org == null) {
                throw new BizException("部门不存在不能分配!", 10001);
            }
            if (null == org.getLeaderId()) {
                throw new BizException("部门领导不存在不能分配!", 10001);
            }
            ruser = repository.get(User.class, org.getLeaderId());
            allotBusinessDept(business, ruser, org, currentLoginUser,0);// 分配到部门
            // allotBusiness(business, ruser, currentLoginUser, cLevel, 1);
            // setBusinessWillDropDate(business);
            business.setUpdaterUser(currentLoginUser);
            setBusinessWillDropDate(business);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 判断商务是否可以接单，若不能接单抛出未接单原因的异常
     *
     * @param ruser 接单用户
     */
    private void isUserCanReceiveBusiness(User ruser, User ouser) {
        if (null == ruser) {
            throw new BizException("商务不存在，不能分配商机", 10001);
        }
        if (ruser.getLocked() != 0) {// 0、正常；1、锁定；2、离职；默认：0、正常
            String msg = "商务状态异常，不能分配商机";
            if (ruser.getLocked() == 1) {
                msg = "商务被锁定，不能分配商机";
            } else if (ruser.getLocked() == 2) {
                msg = "商务已经离职，不能分配商机";
            }
            throw new BizException(msg, 10001);
        }
        // 禁用截止时间 不为空而且大于当前时间
        if (null != ruser.getDisableCutoffTime() && ruser.getDisableCutoffTime().getTime() > new Date().getTime()) {
            throw new BizException("商务在" + DateUtil.dateToString(ruser.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，无法接收资源", 10001);
        }
        // todo 暂时注释掉
//        String onlineStateCodes = ConfigLoader.getConfigLoader().getVaule("onlineUserCodes").trim();
//        List<String> onlineStateCodeArray = Arrays.asList(onlineStateCodes.split(";"));
//        if (StringUtils.isBlank(ruser.getStateType()) || !onlineStateCodeArray.contains(ruser.getStateType())) {
//            throw new BizException("商务当前不在线，不能分配商机", 10001);
//        }
        // 判断是否设置接单规则
        UserSetting us = repository.get(UserSetting.class, ruser.getId());
        if (null == us || null == us.getMonthNum()) {
            throw new BizException("商务未设置接单规则，无法接单", 10001);
        }
        // 判断今日是否可以接单
        if (null == us.getIsReceive() || us.getIsReceive() != 1) {
            // 获取不可以接单的原因
            String reson = "商务已关闭接单，无法接单";
            if (null != us.getIsForce() && 0 != us.getIsForce()) {// 强制不接单不为空
                reson = us.getIsForce() == 1 ? "商务昨日值班，今日不再分资源。" : "商务昨日掉库率达到上限，今日不能接收资源";
            }
            throw new BizException(reson, 10001);
        }

        // redis判断商务5分钟内是否有操作，没有的话代表不在线
        // 获取用户最后一次操作时间戳
        Long timestemp = CacheManager.getOperator().get(Constants.USER_SESSION_LAST_OPT_PREFIX + ruser.getId(), Long.class);
        timestemp = null == timestemp ? 0L : timestemp;
        try {
            TreeBook tb = treeBookService.queryTreeBookByCode("LXFZS");
            // 获取最大间隔时间
            Long maxIdle = (null == tb || tb.getStatus() != 1 || StringUtils.isBlank(tb.getExt1())) ? 99999L : Long.valueOf(tb.getExt1());
            maxIdle = 1000 * 60 * maxIdle;
            // 如果超过了最大间隔
            if (System.currentTimeMillis() - timestemp > maxIdle) {
                throw new BizException("商务当前已掉线，不能分配商机", 10001);
            }
        } catch (Exception e) {
            logger.error("判断商务是否在线出现异常：" + e.getMessage());
        }

        // 判断月接单量
        List<Map> counts = businessAllotCountService.searchUserAllotRecord(ruser.getId(), DateUtil.dateToString(new Date(), "yyyyMM"));
        if (null != counts && !counts.isEmpty()) {
            Integer all = 0;
            for (Map count : counts) {
                all += Integer.valueOf(count.get("allotnumber").toString());
            }
            if (all >= us.getMonthNum()) {
                throw new BizException("商务月接单量已满，无法接单", 10001);
            }
        }

    }

    /**
     * 判断商务是否可以接单，若不能接单抛出未接单原因的异常
     *
     * @param ruser 接单用户
     */
    private void isUserCanReceiveBusiness(User ruser) {
        // todo 暂时注释掉
//        String onlineStateCodes = ConfigLoader.getConfigLoader().getVaule("onlineUserCodes").trim();
//        List<String> onlineStateCodeArray = Arrays.asList(onlineStateCodes.split(";"));
//        if (StringUtils.isBlank(ruser.getStateType()) || !onlineStateCodeArray.contains(ruser.getStateType())) {
//            throw new BizException("商务当前不在线，不能分配商机", 10001);
//        }
        if (null != ruser.getDisableCutoffTime() && ruser.getDisableCutoffTime().getTime() > new Date().getTime()) {
            throw new BizException("商务在" + DateUtil.dateToString(ruser.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，不能接单", 10001);
        }
        // 判断是否设置接单规则
        UserSetting us = repository.get(UserSetting.class, ruser.getId());
        if (null == us || null == us.getMonthNum()) {
            throw new BizException("商务未设置接单规则，无法接单", 10001);
        }
        // 判断今日是否可以接单
        if (null == us.getIsReceive() || us.getIsReceive() != 1) {
            // 获取不可以接单的原因
            String reson = "商务已关闭接单，无法接单";
            if (null != us.getIsForce() && 0 != us.getIsForce()) {// 强制不接单不为空
                reson = us.getIsForce() == 1 ? "商务昨日值班，今日不再分资源。" : "商务昨日掉库率达到上限，今日不能接收资源";
            }
            throw new BizException(reson, 10001);
        }

        // redis判断商务5分钟内是否有操作，没有的话代表不在线
        // 获取用户最后一次操作时间戳
        Long timestemp = CacheManager.getOperator().get(Constants.USER_SESSION_LAST_OPT_PREFIX + ruser.getId(), Long.class);
        timestemp = null == timestemp ? 0L : timestemp;
        try {
            TreeBook tb = treeBookService.queryTreeBookByCode("LXFZS");
            // 获取最大间隔时间
            Long maxIdle = (null == tb || tb.getStatus() != 1 || StringUtils.isBlank(tb.getExt1())) ? 99999L : Long.valueOf(tb.getExt1());
            maxIdle = 1000 * 60 * maxIdle;
            // 如果超过了最大间隔
            if (System.currentTimeMillis() - timestemp > maxIdle) {
                throw new BizException("商务当前已掉线，不能抢单", 10001);
            }
        } catch (Exception e) {
            logger.error("判断商务是否在线出现异常：" + e.getMessage());
        }

        // 判断月接单量
        List<Map> counts = businessAllotCountService.searchUserAllotRecord(ruser.getId(), DateUtil.dateToString(new Date(), "yyyyMM"));
        if (null != counts && !counts.isEmpty()) {
            Integer all = 0;
            for (Map count : counts) {
                all += Integer.valueOf(count.get("allotnumber").toString());
            }
            if (all >= us.getMonthNum()) {
                throw new BizException("商务月接单量已满，无法接单", 10001);
            }
        }

    }

    /**
     * 判断商务库资源是否超过事业部库容量
     *
     * @param map
     */
    private void isMoreThanSybNum(Map map, Long organizationId) {
        // 判断库容量是否已经满了，满了则不能接单
        int syb_num = businessDao.countBusinessSybNumByMap(map);
        String nums = ruleConfigService.getRuleConfigByMap(organizationId, "GZFL_SYB_NUM");
        if (null != nums && syb_num >= NumberUtils.toInt(nums)) {
            throw new BizException("商务库容量已满！", 10001);
        }
    }

    /**
     * 未分配的商机进行无效处理
     *
     * @param businessId       商机id
     * @param currentLoginUser 操作人
     */
    public void deleteBusiness(Long businessId, User currentLoginUser) {
        BizExceptionUtil.isException(null == businessId, "请传入商机id");
        Business oldInfo = getBusinessById(businessId);
        BizExceptionUtil.isException(null == oldInfo, "商机不存在");
        BizExceptionUtil.isException(null == oldInfo.getBusinessStatus() || !oldInfo.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW), "商机状态已更新,无法剔除");
        BizExceptionUtil.isException(null == oldInfo.getBusinessLocation() || oldInfo.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_SOURCE, "商机所在库已更新,无法剔除");
        oldInfo.setLastFollowRecordContent("资源端剔除");
        oldInfo.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ALLOTER_DELETE);
        oldInfo.setBusinessLocation(BusinessConstant.BUS_STORE_INVALID);// 无效库
        oldInfo.setLoseDeptTime(new Date());
        oldInfo.setIsImportant(0);
        oldInfo.setIsVip(0);
        oldInfo.setLastFollowRecordTime(new Date());
        oldInfo.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
        // 新增反无效数据库的数据
        AntiInvalid ai = new AntiInvalid();
        ai.setId(keyWorker.nextId());
        ai.setCreateUser(currentLoginUser);
        ai.setCustomerId(oldInfo.getCustomerId());
        ai.setBusinessId(oldInfo.getId());
        ai.setAntiInvalidReason("资源端剔除");
        ai.setAntiInvalidReviewerId(currentLoginUser.getId());
        ai.setAntiInvalidReviewerName(oldInfo.getLastFollowRecordUser());
        ai.setAntiInvalidUserOrgId(currentLoginUser.getOrgId());
        ai.setAntiInvalidTime(new Date());// 这个更新时间并不是最好的方式，最好是从返无效记录里面去找
        ai.setAntiInvalidUserName(currentLoginUser.getName() + currentLoginUser.getLoginName());
        ai.setAntiInvalidUserId(currentLoginUser.getId());
        repository.save(ai);
        saveBusinessRecord(oldInfo, oldInfo.getBusinessOperate(), "资源端剔除", currentLoginUser.getId(), null, null, null, null, "", "");
        repository.saveOrUpdate(oldInfo);
    }

    /**
     * 资源端修改商机信息
     *
     * @param reqParam 页面参数
     * @param business 商机新内容
     * @param user     操作用户
     */
    public void editBusiness(Map reqParam, Business business, User user) {
        Business oldInfo = getBusinessById(business.getId());
        if ((!oldInfo.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_NEW) && !oldInfo.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN))) {
            throw new BizException("商机状态已更改，不能进行修改，请刷新", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == business.getBusinessOrganizationId()) {
            throw new BizException("受理事业部为空，无法操作", 10001);
        }
        if (null == user) {
            throw new BizException("修改人为空，无法操作", 10001);
        }
        String areaName = reqParam.get("areaName") == null ? "" : reqParam.get("areaName").toString();
        if (StringUtils.isBlank(areaName)) {
            throw new BizException("业务区域为空，无法操作", 10001);
        }
        oldInfo.setCustomerName(business.getCustomerName());
        Map cus = new HashMap();
        cus.put("name", business.getCustomerName());
        cus.put("age", reqParam.get("age"));
        cus.put("address", reqParam.get("address"));
        cus.put("email", reqParam.get("email"));
        cus.put("birthday", reqParam.get("birthday"));
        cus.put("registeredResidence", reqParam.get("registeredResidence"));
        cus.put("idCard", reqParam.get("idCard"));
        cus.put("sex", reqParam.get("sex"));
        cus.put("maritalStatus", reqParam.get("maritalStatus"));
        cus.put("eduBackground", reqParam.get("eduBackground"));
        cus.put("origin", business.getOriginCode());
        cus.put("originName", reqParam.get("originCodeName"));
        cus.put("User", user);
        cus.put("id", oldInfo.getCustomerId());
        cus.put("business", business);
        Customer customer = customerApiService.updateCustomer(cus);
        //商机判重
        if (oldInfo.getBusinessOrganizationId().longValue() != business.getBusinessOrganizationId().longValue() || !business.getTypeCode().equals(oldInfo.getTypeCode())) {
            oldInfo.setBusinessOrganizationId(business.getBusinessOrganizationId());
            Map existed = new HashMap();
            existed.put("customerId", customer.getId());
            existed.put("notInBusinessLocation", "6");
            String centerIds = null;
//			existed.put("notInBusinessLocation", String.valueOf(BusinessConstant.BUS_STORE_DEPARTMENT + "," + BusinessConstant.BUS_STORE_INVALID));
//            existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_SUCCESSED + "','" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//			existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//            Integer count = businessDao.countBusinessByMap(existed);
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
            if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                //	Long orgId = organizationService.getOrganizatioComploy(business.getBusinessOrganizationId());
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else {//全集团

            }
            List<Map> list = businessDao.listBusinessByMap(existed);
            if (!oldInfo.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_5)) { //资源端新建
                //资源端新建
            }
            if (null != list && !list.isEmpty()) {
                existed.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                String day = null;
                if (NumberUtils.toInt(tb.getExt1()) != 0) {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()) + 1);
                    day = workDayDao.queryBeforeDate(existed);
                } else {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()));
                }

                day = workDayDao.queryBeforeDate(existed);
                boolean ex = false;
                for (Map map : list) {
                    if (NumberUtils.toInt(map.get("businessLocation") + "") != 1 && NumberUtils.toInt(map.get("businessLocation") + "") != 2 && NumberUtils.toInt(map.get("businessLocation") + "") != 5) {
                        ex = true;
                        break;
                    }
                    if (!map.get("id").toString().equals(oldInfo.getId().toString())) {
                        boolean businessStatus = BusinessConstant.BUS_STATUS_SIGNED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(String.valueOf(map.get("businessStatus")));
                        if (businessStatus) {
                            if (map.get("orderTime") != null && StringUtils.isNotEmpty(day)) {
                                String orderTime = map.get("orderTime").toString();
                                int i = DateUtil.compare_date(day + " 00:00:00", orderTime);
                                if (i == 1) {
                                    ex = false;
                                } else {
                                    ex = true;
                                    break;
                                }
                            }

                        } else {
                            ex = true;
                            break;
                        }
                    }

                }
                BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");

            }
        }

        oldInfo.setTypeCode(business.getTypeCode());
        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea("");
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
            business.setCity("");
            business.setArea("");
        }
        oldInfo.setArea(business.getArea());
        oldInfo.setCity(business.getCity());
        oldInfo.setProvince(business.getProvince());

        oldInfo.setLoadInterrestValue(business.getLoadInterrestValue());
        oldInfo.setLoanInterrestRate(business.getLoanInterrestRate());
        oldInfo.setLoanTime(business.getLoanTime());
        oldInfo.setLoanAmount(business.getLoanAmount());
        oldInfo.setLoanCycle(business.getLoanCycle());
        oldInfo.setRepaymentType(business.getRepaymentType());
        oldInfo.setBusinessSourceCode(business.getBusinessSourceCode());
        oldInfo.setExtensionCode(business.getExtensionCode());
        oldInfo.setUrl(business.getUrl());
        oldInfo.setDescription(business.getDescription());
        oldInfo.setKeyWord(business.getKeyWord());
        oldInfo.setOriginCode(business.getOriginCode());
        oldInfo.setIsCost(business.getIsCost());
        oldInfo.setIsCost("CBJSFS_NO");// 不需要计算成本
        oldInfo.setCostPrice(business.getCostPrice());
        // 资源端新增计算成本
//            Long cost = getCosts(business.getBusinessOrganizationId()+"",business.getTypeCode(),business.getOrigincodeType());
//            if(cost.longValue()>1){
//                oldInfo.setIsCost("yes");
//                oldInfo.setCostPrice(cost.intValue());
//            }else{
//                oldInfo.setIsCost("CBJSFS_NO");
//				oldInfo.setCostPrice(cost.intValue());
//            }

        String businessType = "";
        // 如果表单资源是 2 3 4 5 类
        if (null != business.getOrigincodeType()
                && (business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_1) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_3)
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_4) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_5)
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_10) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_11) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_12))
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_13) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_14)) {
            if (business.getTypeCode().contains("BUS_YT_DYDK")) {
                businessType = "rzdy";

            } else if (business.getTypeCode().contains("BUS_YT_XYDK")) {
                businessType = "rzxd";
            } else {
                businessType = "rzxd";
            }
            String place = treeBookService.queryTreeBookByCode(business.getBusinessOrganizationId().toString()).getExt4();
            Map newPriceMap = new HashMap();
            newPriceMap.put("busCode", "BUS_YT_DK");
            newPriceMap.put("placeCode", "BUS_SOR_PLACE_" + place);
            newPriceMap.put("type", businessType);
            newPriceMap.put("typeCode", business.getTypeCode());
            newPriceMap.put("tel", njCodeUtil.decrypt(business.getCustomerPhone()));
            newPriceMap.put("city", place);
            newPriceMap.put("originType", business.getOrigincodeType());
            Map priceMap = getCostPriceByOriginType(newPriceMap);
            Map ob = (Map) priceMap.get("data");
            if (priceMap.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                // throw new BizException(priceMap.get("msg").toString(), 10001);
                oldInfo.setIsCost("yes");// 需要计算成本
                oldInfo.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
            } else {
                oldInfo.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
                oldInfo.setIsCost("CBJSFS_NO");// 不需要计算成本
            }
        }
        // 重新计算成本，根据渠道查询计算成本的方式及值
//		if (null != business.getIsCost() && business.getIsCost().equals("yes")) {
//			ChannelCost coc = null;
//			List<ChannelCost> list = repository.findByProperty(ChannelCost.class, "channelCode", oldInfo.getOriginCode());
//			if (null != list && !list.isEmpty()) {
//				coc = list.get(0);
//			}
//			if (null == coc || coc.getStatus() != 1) {//不存在或未启用的都不计算成本
//				oldInfo.setIsCost("CBJSFS_NO");
//				oldInfo.setCostPrice(0);
//			} else {
//				oldInfo.setIsCost(coc.getCostType());
//
//				oldInfo.setCostPrice(coc.getCost());
//			}
//		}
        oldInfo.setUpdaterUser(user);
        // 资源端是否立即分配
        String allot = reqParam.get("allot") == null ? "" : reqParam.get("allot").toString();
        if ("1".equals(allot)) {
            if (oldInfo.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT)) {
                throw new BizException("商机已在自动分配队列中，请耐心等待!", 10001);
            }
            allotBusiness(oldInfo, null, user, customer.getLevel(), 2, 1);
        }
        if (!oldInfo.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_ZYD_SHUIHUI)) {
            oldInfo.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_EDIT);
        }
        oldInfo.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        oldInfo.setOrigincodeType(business.getOrigincodeType());// 来源渠道方式
        repository.saveOrUpdate(oldInfo);
        saveBusinessRecord(oldInfo, CustomerRecordConstant.BUS_OPERATE_EDIT, "修改了商机信息", user.getId(), null, null);
    }

    /**
     * 资源端修改商机信息
     *
     * @param reqParam 页面参数
     * @param business 商机新内容
     * @param user     操作用户
     */
    public void editTwoBusiness(Map reqParam, Business business, User user) {
        Business oldInfo = getBusinessById(business.getId());
        if (!oldInfo.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN)) {
            throw new BizException("商机状态已更改，不能进行修改，请刷新", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == business.getBusinessOrganizationId()) {
            throw new BizException("受理事业部为空，无法操作", 10001);
        }
        if (null == user) {
            throw new BizException("修改人为空，无法操作", 10001);
        }
        String areaName = reqParam.get("areaName") == null ? "" : reqParam.get("areaName").toString();
        if (StringUtils.isBlank(areaName)) {
            throw new BizException("业务区域为空，无法操作", 10001);
        }
        oldInfo.setCustomerName(business.getCustomerName());

        Map cus = new HashMap();
        cus.put("name", business.getCustomerName());
        cus.put("age", reqParam.get("age"));
        cus.put("address", reqParam.get("address"));
        cus.put("email", reqParam.get("email"));
        cus.put("birthday", reqParam.get("birthday"));
        cus.put("registeredResidence", reqParam.get("registeredResidence"));
        cus.put("idCard", reqParam.get("idCard"));
        cus.put("sex", reqParam.get("sex"));
        cus.put("maritalStatus", reqParam.get("maritalStatus"));
        cus.put("eduBackground", reqParam.get("eduBackground"));
        cus.put("origin", business.getOriginCode());
        cus.put("originName", reqParam.get("originCodeName"));
        cus.put("User", user);
        cus.put("id", oldInfo.getCustomerId());
        cus.put("business", business);
        Customer customer = customerApiService.updateCustomer(cus);
        //商机判重
        if (oldInfo.getBusinessOrganizationId().longValue() != business.getBusinessOrganizationId().longValue() || !business.getTypeCode().equals(oldInfo.getTypeCode())) {
            oldInfo.setBusinessOrganizationId(business.getBusinessOrganizationId());
            Map existed = new HashMap();
            existed.put("customerId", customer.getId());
            existed.put("notInBusinessLocation", "6");
            String centerIds = null;
//			existed.put("notInBusinessLocation", String.valueOf(BusinessConstant.BUS_STORE_DEPARTMENT + "," + BusinessConstant.BUS_STORE_INVALID));
//            existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_SUCCESSED + "','" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//			existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//            Integer count = businessDao.countBusinessByMap(existed);
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
            if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                //	Long orgId = organizationService.getOrganizatioComploy(business.getBusinessOrganizationId());
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else {//全集团

            }
            List<Map> list = businessDao.listBusinessByMap(existed);
            if (!oldInfo.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_5)) { //资源端新建
                //资源端新建
            }
            if (null != list && !list.isEmpty()) {
                existed.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                String day = null;
                if (NumberUtils.toInt(tb.getExt1()) != 0) {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()) + 1);
                    day = workDayDao.queryBeforeDate(existed);
                } else {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()));
                }
                day = workDayDao.queryBeforeDate(existed);
                boolean ex = false;
                for (Map map : list) {
                    if (NumberUtils.toInt(map.get("businessLocation") + "") != 1 && NumberUtils.toInt(map.get("businessLocation") + "") != 2 && NumberUtils.toInt(map.get("businessLocation") + "") != 5) {
                        ex = true;
                        break;
                    }
                    if (!map.get("id").toString().equals(oldInfo.getId().toString())) {
                        boolean businessStatus = BusinessConstant.BUS_STATUS_SIGNED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(String.valueOf(map.get("businessStatus")));
                        if (businessStatus) {
                            if (map.get("orderTime") != null && StringUtils.isNotEmpty(day)) {
                                String orderTime = map.get("orderTime").toString();
                                int i = DateUtil.compare_date(day + " 00:00:00", orderTime);
                                if (i == 1) {
                                    ex = false;
                                } else {
                                    ex = true;
                                    break;
                                }
                            }

                        } else {
                            ex = true;
                            break;
                        }
                    }

                }
                BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");

            }
        }
        oldInfo.setBusinessOrganizationId(business.getBusinessOrganizationId());
        oldInfo.setTypeCode(business.getTypeCode());
        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea("");
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
            business.setCity("");
            business.setArea("");
        }
        oldInfo.setArea(business.getArea());
        oldInfo.setCity(business.getCity());
        oldInfo.setProvince(business.getProvince());

        oldInfo.setLoadInterrestValue(business.getLoadInterrestValue());
        oldInfo.setLoanInterrestRate(business.getLoanInterrestRate());
        oldInfo.setLoanTime(business.getLoanTime());
        oldInfo.setLoanAmount(business.getLoanAmount());
        oldInfo.setLoanCycle(business.getLoanCycle());
        oldInfo.setRepaymentType(business.getRepaymentType());
        oldInfo.setBusinessSourceCode(business.getBusinessSourceCode());
        oldInfo.setExtensionCode(business.getExtensionCode());
        oldInfo.setUrl(business.getUrl());
        oldInfo.setDescription(business.getDescription());
        oldInfo.setKeyWord(business.getKeyWord());
        oldInfo.setOriginCode(business.getOriginCode());
        oldInfo.setIsCost(business.getIsCost());
        oldInfo.setIsCost("CBJSFS_NO");// 不需要计算成本
        oldInfo.setCostPrice(business.getCostPrice());
        // 资源端新增计算成本
//            Long cost = getCosts(business.getBusinessOrganizationId()+"",business.getTypeCode(),business.getOrigincodeType());
//            if(cost.longValue()>1){
//                oldInfo.setIsCost("yes");
//                oldInfo.setCostPrice(cost.intValue());
//            }else{
//                oldInfo.setIsCost("CBJSFS_NO");
//				oldInfo.setCostPrice(cost.intValue());
//            }

        String businessType = "";
        // 如果表单资源是 2 3 4 5 类
        if (null != business.getOrigincodeType()
                && (business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_1) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_3)
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_4) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_5) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_10) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_11) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_12))
                || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_13) || business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_14)) {
            if (business.getTypeCode().contains("BUS_YT_DYDK")) {
                businessType = "rzdy";

            } else if (business.getTypeCode().contains("BUS_YT_XYDK")) {
                businessType = "rzxd";
            } else {
                businessType = "rzxd";
            }
            String place = treeBookService.queryTreeBookByCode(business.getBusinessOrganizationId().toString()).getExt4();
            Map newPriceMap = new HashMap();
            newPriceMap.put("busCode", "BUS_YT_DK");
            newPriceMap.put("placeCode", "BUS_SOR_PLACE_" + place);
            newPriceMap.put("type", businessType);
            newPriceMap.put("typeCode", business.getTypeCode());
            newPriceMap.put("tel", njCodeUtil.decrypt(business.getCustomerPhone()));
            newPriceMap.put("city", place);
            newPriceMap.put("originType", business.getOrigincodeType());
            Map priceMap = getCostPriceByOriginType(newPriceMap);
            Map ob = (Map) priceMap.get("data");
            if (priceMap.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                // throw new BizException(priceMap.get("msg").toString(), 10001);
                oldInfo.setIsCost("yes");// 需要计算成本
                oldInfo.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
            } else {
                oldInfo.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
                oldInfo.setIsCost("CBJSFS_NO");// 不需要计算成本
            }
        }
        // 重新计算成本，根据渠道查询计算成本的方式及值
//		if (null != business.getIsCost() && business.getIsCost().equals("yes")) {
//			ChannelCost coc = null;
//			List<ChannelCost> list = repository.findByProperty(ChannelCost.class, "channelCode", oldInfo.getOriginCode());
//			if (null != list && !list.isEmpty()) {
//				coc = list.get(0);
//			}
//			if (null == coc || coc.getStatus() != 1) {//不存在或未启用的都不计算成本
//				oldInfo.setIsCost("CBJSFS_NO");
//				oldInfo.setCostPrice(0);
//			} else {
//				oldInfo.setIsCost(coc.getCostType());
//
//				oldInfo.setCostPrice(coc.getCost());
//			}
//		}
        oldInfo.setUpdaterUser(user);
        if (!oldInfo.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_ZYD_SHUIHUI)) {
            oldInfo.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_EDIT);
        }
        // 资源端是否立即分配
        String allot = reqParam.get("allot") == null ? "" : reqParam.get("allot").toString();
        if ("1".equals(allot)) {
            if (oldInfo.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_AUTO_ALLOT)) {
                throw new BizException("商机已在自动分配队列中，请耐心等待!", 10001);
            }
            allotBusiness(oldInfo, null, user, customer.getLevel(), 2, 1);
        }
        oldInfo.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        oldInfo.setOrigincodeType(business.getOrigincodeType());// 来源渠道方式
        repository.saveOrUpdate(oldInfo);
        saveBusinessRecord(oldInfo, CustomerRecordConstant.BUS_OPERATE_EDIT, "修改了商机信息", user.getId(), null, null);
    }

    /**
     * 转介绍修改商机信息
     *
     * @param reqParam 页面参数
     * @param business 商机新内容
     * @param user     操作用户
     */
    public void editReferralBusiness(Map reqParam, Business business, BusinessReferral businessReferral, User user, User referralUser, User reciveUser) {
        Business oldInfo = getBusinessById(business.getId());
        if (!oldInfo.getBusinessStatus().equals(BusinessConstant.BUS_WAIT_ALLOT_AGAIN)) {
            throw new BizException("商机状态已更改，不能进行修改，请刷新", 10001);
        }
        if (null == business.getTypeCode()) {
            throw new BizException("商机业态为空，无法操作", 10001);
        }
        if (null == business.getBusinessOrganizationId()) {
            throw new BizException("受理事业部为空，无法操作", 10001);
        }
        if (null == user) {
            throw new BizException("修改人为空，无法操作", 10001);
        }
        String areaName = reqParam.get("areaName") == null ? "" : reqParam.get("areaName").toString();
        if (StringUtils.isBlank(areaName)) {
            throw new BizException("业务区域为空，无法操作", 10001);
        }
        oldInfo.setCustomerName(business.getCustomerName());
        oldInfo.setTypeCode(business.getTypeCode());
        Map cus = new HashMap();
        cus.put("name", business.getCustomerName());
        cus.put("age", reqParam.get("age"));
        cus.put("address", reqParam.get("address"));
        cus.put("email", reqParam.get("email"));
        cus.put("birthday", reqParam.get("birthday"));
        cus.put("registeredResidence", reqParam.get("registeredResidence"));
        cus.put("idCard", reqParam.get("idCard"));
        cus.put("sex", reqParam.get("sex"));
        cus.put("maritalStatus", reqParam.get("maritalStatus"));
        cus.put("eduBackground", reqParam.get("eduBackground"));
        cus.put("origin", business.getOriginCode());
        cus.put("originName", reqParam.get("originCodeName"));
        cus.put("User", user);
        cus.put("id", oldInfo.getCustomerId());
        cus.put("business", business);
        Customer customer = customerApiService.updateCustomer(cus);
//商机判重
        if (oldInfo.getBusinessOrganizationId().longValue() != business.getBusinessOrganizationId().longValue() || !business.getTypeCode().equals(oldInfo.getTypeCode())) {
            Map existed = new HashMap();
            existed.put("customerId", customer.getId());
            existed.put("notInBusinessLocation", "6");
            String centerIds = null;
            oldInfo.setBusinessOrganizationId(business.getBusinessOrganizationId());
//			existed.put("notInBusinessLocation", String.valueOf(BusinessConstant.BUS_STORE_DEPARTMENT + "," + BusinessConstant.BUS_STORE_INVALID));
//            existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_SUCCESSED + "','" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//			existed.put("notInBusinessStatus", "'" + BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
//            Integer count = businessDao.countBusinessByMap(existed);
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
            if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                //	Long orgId = organizationService.getOrganizatioComploy(business.getBusinessOrganizationId());
                existed.put("businessOrganizationId", business.getBusinessOrganizationId() + "");
            } else {//全集团

            }
            List<Map> list = businessDao.listBusinessByMap(existed);
            if (!oldInfo.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_5)) { //资源端新建
                //资源端新建
            }
            if (null != list && !list.isEmpty()) {
                existed.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                String day = null;
                if (NumberUtils.toInt(tb.getExt1()) != 0) {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()) + 1);
                    day = workDayDao.queryBeforeDate(existed);
                } else {
                    existed.put("days", NumberUtils.toInt(tb.getExt1()));
                }
                day = workDayDao.queryBeforeDate(existed);
                boolean ex = false;
                for (Map map : list) {
                    if (NumberUtils.toInt(map.get("businessLocation") + "") != 1 && NumberUtils.toInt(map.get("businessLocation") + "") != 2 && NumberUtils.toInt(map.get("businessLocation") + "") != 5) {
                        ex = true;
                        break;
                    }
                    if (!map.get("id").toString().equals(oldInfo.getId().toString())) {
                        boolean businessStatus = BusinessConstant.BUS_STATUS_SIGNED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(String.valueOf(map.get("businessStatus"))) || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(String.valueOf(map.get("businessStatus")));
                        if (businessStatus) {
                            if (map.get("orderTime") != null && StringUtils.isNotEmpty(day)) {
                                String orderTime = map.get("orderTime").toString();
                                int i = DateUtil.compare_date(day + " 00:00:00", orderTime);
                                if (i == 1) {
                                    ex = false;
                                } else {
                                    ex = true;
                                    break;
                                }
                            }
                        } else {
                            ex = true;
                            break;
                        }
                    }
                }
                BizExceptionUtil.isException(ex, "客户已有正在办理中的业务，不可以新建商机");

            }
        }
        oldInfo.setTypeCode(business.getTypeCode());
        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea("");
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
            business.setCity("");
            business.setArea("");
        }
        oldInfo.setArea(business.getArea());
        oldInfo.setCity(business.getCity());
        oldInfo.setProvince(business.getProvince());
        oldInfo.setUpdaterUser(user);
        oldInfo.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_EDIT);
        oldInfo.setDescription(HtmlUtils.htmlEscape(business.getDescription()));
        oldInfo.setOrigincodeType(business.getOrigincodeType());// 来源渠道方式
        // 如果是转介绍商机
        BusinessReferral oldBusinessReferral = businessReferralService.getBusinessReferralById(business.getId());
        oldBusinessReferral.setUpdaterUser(user);
        oldBusinessReferral.setReferralUserId(referralUser.getId());
        oldBusinessReferral.setReferralOrgId(referralUser.getOrgId());
        oldBusinessReferral.setReferralUserName(referralUser.getName() + referralUser.getLoginName());
        Long orgId = organizationService.getOrganizationDepartmentId(referralUser.getOrgId());
        businessReferral.setReferralOrganizationId(orgId);
        if (!TranslateMapUtil.translateOrgName(orgId).equals("null") && TranslateMapUtil.translateOrgName(orgId).length() > 0) {
            businessReferral.setReferralOrganizationName(TranslateMapUtil.translateOrgName(orgId));
        }
        oldBusinessReferral.setReceiveUserId(reciveUser.getId());
        oldBusinessReferral.setReceiveUserName(reciveUser.getName() + reciveUser.getLoginName());
        oldBusinessReferral.setReceiveOrgId(reciveUser.getOrgId());
        if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_HFYJ)) {
        } else if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_FFTC)) {
            // 进入质检待审核
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 质检待审核设置待跟进
            business.setBusinessLocation(BusinessConstant.BUS_STORE_REFERRAl);// 转介绍库
            business.setBusinessOperate(CustomerRecordConstant.BUS_1009);// 当前操作为质检待审核
            businessReferral.setReferralAuditStatus(0);
        }
        oldBusinessReferral.setRewardWay(businessReferral.getRewardWay());
        oldBusinessReferral.setReferralRed(businessReferral.getReferralRed());
        oldBusinessReferral.setReferralType(businessReferral.getReferralType());
        business.setDescription(business.getDescription());// 留言
        repository.saveOrUpdate(oldBusinessReferral);
        repository.saveOrUpdate(oldInfo);
        saveBusinessRecord(oldInfo, CustomerRecordConstant.BUS_OPERATE_EDIT, "修改了商机信息", user.getId(), null, null);
    }

    /**
     * 统计商机记录条数
     *
     * @param map
     * @return
     */
    public Integer countBusinessRecordByMap(Map map) {
        return businessDao.countBusinessRecordByMap(map);
    }

    /**
     * 查询商机记录列表
     *
     * @param map
     * @return
     */
    public List<Map> listBusinessRecordByMap(Map map) {
        return businessDao.listBusinessRecordByMap(map);
    }

    /**
     * 统计转介绍商机记录条数
     *
     * @param map
     * @return
     */
    public Integer countReferralBusinessRecordByMap(Map map) {

        return businessDao.countReferralBusinessRecordByMap(map);
    }

    /**
     * 查询转介绍商机记录列表
     *
     * @param map
     * @return
     */
    public List<Map> listReferralBusinessRecordByMap(Map map) {
        return businessDao.listReferralBusinessRecordByMap(map);
    }

    /**
     * 批量移交商机
     *
     * @param businessIds      商机id集合，以,号分割
     * @param currentLoginUser 当前操作人
     * @param userId           商机接收人id
     */
    public void moveBusiness(String businessIds, User currentLoginUser, Long userId, String reson) {
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要移交的商机", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            if (null == business
                    || (!business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_EMP) && !business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_ORG))) {
                throw new BizException("商机不存在或已掉库，请查询后再试", 10001);
            }
            // 已签单的商机可以进行移交
//            if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
//                throw new BizException("商机【" + business.getNo() + "】正在处理做订单处理，不能移交", 10001);
//            }
            // 判断不能移交的情况
            String currentOperate = business.getBusinessOperate();
//            if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_HIDE) || currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_INVALID)) {
            if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_INVALID)) {
                throw new BizException("商机【" + business.getNo() + "】正在等待返无效审核，不能进行移交", 10001);
            }

            User ruser = repository.get(User.class, userId);
            if (null == ruser) {
                throw new BizException("接收人不存在，不能移交商机", 10001);
            }
            if (null != ruser.getDisableCutoffTime() && ruser.getDisableCutoffTime().getTime() > new Date().getTime()) {
                throw new BizException("商务在" + DateUtil.dateToString(ruser.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，无法接收资源", 10001);
            }
            // 判断库容量是否已经满了，满了则不能接单
            // if (null != business.getOpportunitytypeCode() &&
            // !business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_5)){
            Map numMap = new HashMap();
            numMap.put("followerId", ruser.getId());
            isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
//        }
            // 判断接收人的角色，如果有商务经理角色，则
            // 如果是商务角色，则判断商机当前的操作，如果是未首电掉给经理,则当前操作不需要更改
            String content = "OPARETA_TYPE【" + ruser.getName() + ruser.getLoginName() + "】." + (StringUtils.isNotBlank(reson) ? "原因:" + reson : "");
            User oldUser = repository.get(User.class, business.getFollowerId());
            if (roleService.userHasRole(ruser, "shangwujingli")) {// 接收人是商务经理
                if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_NOCALL_LEADER)) {
                    // 未首电平移给商务经理，操作就变成强制移交经理
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER);
                    // 发送短信给接收的人
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    content = content.replace("OPARETA_TYPE", "未首电移交给商务经理");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, null);// 没有入库也没有出库
                } else if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER)) {// 经理之间的平移
                    content = content.replace("OPARETA_TYPE", "移交给商务经理");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, null);// 没有入库也没有出库
                } else {// 从商务手上移交给经理
                    // 发送短信给接收的人、被移交的商务
                    content = content.replace("OPARETA_TYPE", "强制移交给商务经理");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    sendBusinessMsg(oldUser, currentLoginUser, "SJ_0011", business.getNo(), !StringUtils.isEmpty(reson) ? reson : "无");
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), oldUser.getId(), null, oldUser.getOrgId(), null,
                            oldUser.getName() + oldUser.getLoginName(), "");// 一出
                }
                // 修改商机事业部为接收人的事业部
                business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
                business.setHandleUserId(ruser.getId());
                business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);
            } else {// 其他人都当作商务处理
                // (跟进人id、商机部门id、事业部id、本次分配时间)为接收人、商机获取方式为移交、 vip标志为0、重点商机标志为0、跟进次数为0
                business.setFollowerName(ruser.getName() + ruser.getLoginName());
                business.setFollowerId(ruser.getId());
                business.setFollowerOrganizationId(ruser.getOrgId());
                business.setWayCode(BusinessConstant.BUS_WAY_CODE_3);
                business.setFollowTimes(0);
                business.setIsVip(0);
                business.setIsImportant(0);
                business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);

                if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_NOCALL_LEADER)) {// 未首电移交给个人
                    // 发送短信给接收的人
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_NOCALL_EMP);
                    content = content.replace("OPARETA_TYPE", "未首电强制移交给商务");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, ruser.getId(), null, ruser.getOrgId(), "",
                            business.getFollowerName());// 一入
                } else if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER)) {// 从平移的经理手上移交给商务
                    content = content.replace("OPARETA_TYPE", "移交给商务");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, ruser.getId(), null, ruser.getOrgId(), "",
                            business.getFollowerName());// 一入
                } else {// 强制移交给个人
                    // 发送短信给接收的人、被移交的商务
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    sendBusinessMsg(oldUser, currentLoginUser, "SJ_0011", business.getNo(), !StringUtils.isEmpty(reson) ? reson : "无");
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP);
                    content = content.replace("OPARETA_TYPE", "强制移交给商务");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), oldUser.getId(), ruser.getId(), oldUser.getOrgId(),
                            ruser.getOrgId(), oldUser.getName() + oldUser.getLoginName(), business.getFollowerName());// 一入、一出
                }
            }
            business.setDistributionTime(new Date());// 移交商务或者移交经理，都把当前分配时间改成当前，用于掉库
            business.setUpdaterUser(currentLoginUser);
            business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
            business.setLastFollowRecordContent(content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowTime(new Date()); // 最新跟进时间
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            setBusinessWillDropDate(business);
            if (null != business.getIsReferral() && business.getIsReferral() == 1) {// 判断商机是否转介绍
                BusinessReferral bf = businessReferralService.getBusinessReferralById(Long.valueOf(id));
                bf.setReceiveUserName(ruser.getName() + ruser.getLoginName());
                bf.setReceiveUserId(ruser.getId());
                bf.setReceiveOrgId(ruser.getOrgId());
                repository.saveOrUpdate(bf);
            }
            repository.saveOrUpdate(business);// 更改接收人
        }

    }

    /**
     * 电销库批量移交商机
     *
     * @param businessIds      商机id集合，以,号分割
     * @param currentLoginUser 当前操作人
     * @param userId           商机接收人id
     */
    public void moveDxBusiness(String businessIds, User currentLoginUser, Long userId, String reson) {
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要移交的商机", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            if (null == business || (!business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_EP))) { // 电销库
                throw new BizException("商机不存在，请查询后再试", 10001);
            }
            // 已签单的商机可以进行移交
//            if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
//                throw new BizException("商机【" + business.getNo() + "】正在处理做订单处理，不能移交", 10001);
//            }
            // 判断不能移交的情况
            String currentOperate = business.getBusinessOperate();
//            if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_HIDE) || currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_INVALID)) {
            if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_INVALID)) {
                throw new BizException("商机【" + business.getNo() + "】正在等待返无效审核，不能进行移交", 10001);
            }

            User ruser = repository.get(User.class, userId);
            if (null == ruser) {
                throw new BizException("接收人不存在，不能移交商机", 10001);
            }
            if (null != ruser.getDisableCutoffTime() && ruser.getDisableCutoffTime().getTime() > new Date().getTime()) {
                throw new BizException("商务在" + DateUtil.dateToString(ruser.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，无法接收资源", 10001);
            }
            // 判断库容量是否已经满了，满了则不能接单
            // if (null != business.getOpportunitytypeCode() &&
            // !business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_5)) {
            Map numMap = new HashMap();
            numMap.put("followerId", ruser.getId());
            isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
            // }
            // 判断接收人的角色，如果有商务经理角色，则
            // 如果是商务角色，则判断商机当前的操作，如果是未首电掉给经理,则当前操作不需要更改
            String content = "OPARETA_TYPE【" + ruser.getName() + ruser.getLoginName() + "】." + (StringUtils.isNotBlank(reson) ? "原因:" + reson : "");
            User oldUser = repository.get(User.class, business.getFollowerId());
            if (roleService.userHasRole(ruser, "shangwujingli")) {// 接收人是商务经理
                if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_NOCALL_LEADER)) {
                    // 未首电平移给商务经理，操作就变成强制移交经理
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER);
                    // 发送短信给接收的人
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    content = content.replace("OPARETA_TYPE", "未首电移交给商务经理");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, null);// 没有入库也没有出库
                } else if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER)) {// 经理之间的平移
                    content = content.replace("OPARETA_TYPE", "移交给商务经理");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, null);// 没有入库也没有出库
                } else if (business.getBusinessLocation() == BusinessConstant.BUS_STORE_EP) {// 如果从电销库移交
                    // 发送短信给接收的人
                    business.setBusTypeDx(CustomerRecordConstant.BUS_OUT_DX); // 电销库移交标示
                    content = content.replace("OPARETA_TYPE", "强制移交给商务经理");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), oldUser.getId(), null, oldUser.getOrgId(), null,
                            oldUser.getName() + oldUser.getLoginName(), "");// 一出
                } else {// 从商务手上移交给经理
                    // 发送短信给接收的人、被移交的商务
                    content = content.replace("OPARETA_TYPE", "强制移交给商务经理");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0009", currentLoginUser.getName(), business.getNo());
                    sendBusinessMsg(oldUser, currentLoginUser, "SJ_0011", business.getNo(), !StringUtils.isEmpty(reson) ? reson : "无");
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), oldUser.getId(), null, oldUser.getOrgId(), null,
                            oldUser.getName() + oldUser.getLoginName(), "");// 一出
                }
                // 修改商机事业部为接收人的事业部
                business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
                business.setHandleUserId(ruser.getId());
                business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);
                business.setVisitStatus(null);
                business.setDistributionTime(new Date());
            } else {// 其他人都当作商务处理
                // (跟进人id、商机部门id、事业部id、本次分配时间)为接收人、商机获取方式为移交、 vip标志为0、重点商机标志为0、跟进次数为0
                business.setFollowerName(ruser.getName() + ruser.getLoginName());
                business.setFollowerId(ruser.getId());
                business.setFollowerOrganizationId(ruser.getOrgId());
                business.setWayCode(BusinessConstant.BUS_WAY_CODE_3);
                business.setFollowTimes(0);
                business.setIsVip(0);
                business.setIsImportant(0);
                business.setDistributionTime(new Date());
                if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_NOCALL_LEADER)) {// 未首电移交给个人
                    // 发送短信给接收的人
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_NOCALL_EMP);
                    content = content.replace("OPARETA_TYPE", "未首电强制移交给商务");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, ruser.getId(), null, ruser.getOrgId(), "",
                            business.getFollowerName());// 一入
                } else if (currentOperate.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_LEADER)) {// 从平移的经理手上移交给商务
                    content = content.replace("OPARETA_TYPE", "移交给商务");
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, ruser.getId(), null, ruser.getOrgId(), "",
                            business.getFollowerName());// 一入
                } else if (business.getBusinessLocation() == BusinessConstant.BUS_STORE_EP) {// 如果从电销库移交
                    content = content.replace("OPARETA_TYPE", "移交给商务");
                    business.setBusTypeDx(CustomerRecordConstant.BUS_OUT_DX); // 电销库移交标示
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP);
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), null, ruser.getId(), null, ruser.getOrgId(), "",
                            business.getFollowerName());// 一入
                } else {// 强制移交给个人
                    // 发送短信给接收的人、被移交的商务
                    sendBusinessMsg(ruser, currentLoginUser, "SJ_0010", currentLoginUser.getName(), business.getNo());
                    sendBusinessMsg(oldUser, currentLoginUser, "SJ_0011", business.getNo(), !StringUtils.isEmpty(reson) ? reson : "无");
                    business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP);
                    content = content.replace("OPARETA_TYPE", "强制移交给商务");
                    saveBusinessRecord(business, business.getBusinessOperate(), content, currentLoginUser.getId(), oldUser.getId(), ruser.getId(), oldUser.getOrgId(),
                            ruser.getOrgId(), oldUser.getName() + oldUser.getLoginName(), business.getFollowerName());// 一入、一出
                }
            }
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);
            // 修改商机事业部为接收人的事业部
            business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(ruser.getOrgId()));
            business.setDistributionTime(new Date());// 移交商务或者移交经理，都把当前分配时间改成当前，用于掉库
            business.setUpdaterUser(currentLoginUser);
            business.setLastFollowRecordContent(content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowTime(new Date()); // 最新跟进时间
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            setBusinessWillDropDate(business);
            if (null != business.getIsReferral() && business.getIsReferral() == 1) {// 判断商机是否转介绍
                BusinessReferral bf = businessReferralService.getBusinessReferralById(Long.valueOf(id));
                bf.setReceiveUserName(ruser.getName() + ruser.getLoginName());
                bf.setReceiveUserId(ruser.getId());
                bf.setReceiveOrgId(ruser.getOrgId());
                repository.saveOrUpdate(bf);
            }
            repository.saveOrUpdate(business);// 更改接收人
        }
    }

    /**
     * 批量质检商机
     *
     * @param businessIds      商机id集合，以,号分割
     * @param currentLoginUser 当前操作人
     * @param userId           商机接收人id
     */
    public void qualityBusiness(String businessIds, User currentLoginUser, Long userId) {
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要质检的商机", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            if (null == business || (!business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_INVALID))) {
                throw new BizException("不存在返无效商机，请查询后再试", 10001);
            }
            User ruser = repository.get(User.class, userId);
            if (null == ruser) {
                throw new BizException("接收人不存在，不能质检商机", 10001);
            }
            sendBusinessMsg(ruser, currentLoginUser, "SJ_0012", currentLoginUser.getName(), business.getNo());
            business.setHandleUserId(userId);
            repository.saveOrUpdate(business);
        }

    }

    /**
     * 批量剔除商机（商务）
     *
     * @param businessIds      商机id集合
     * @param content          剔除原因
     * @param currentLoginUser 操作人
     */
    public void deleteBusiness(String businessIds, String content, User currentLoginUser) {
        Integer businesslocation;
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要剔除的商机", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入剔除原因", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            // 判断商机是否在个人库，且跟进人为操作人
            if (business.getBusinessLocation() != BusinessConstant.BUS_STORE_EMP) {
                throw new BizException("商机【" + business.getNo() + "】当前状态不能进行剔除", 10001);
            }
            if (business.getFollowerId().longValue() != currentLoginUser.getId()) {
                throw new BizException("你不是商机【" + business.getNo() + "】的跟进人，不能进行剔除", 10001);
            }
//			if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
//				//     throw new BizException("商机正在做订单处理，不能进行剔除", 10001);
//				//已签单的商机但是在订单那边没有数据，可以剔除
//				Map businessMap = new HashMap();
//				businessMap.put("businessId", id);
//				List<Map> orderMaps = orderService.queryOrderByBusinessByMap(businessMap);
//				if (null != orderMaps && !orderMaps.isEmpty()) {
//					throw new BizException("商机正在做订单处理，不能进行剔除", 10001);
//				}
//			}
            // 给部门经理发短信，提醒他进行审核
//			Map userMap = new HashMap();
//			userMap.put("rootOrgId", currentLoginUser.getOrgId());
////            userMap.put("userRole", "7");//7代表商务经理
//			userMap.put("userRoleCodes", "shangwujingli");
//			PageData<Map> leaders = userService.searchUser(userMap);
//			if (null == leaders || null == leaders.getData() || leaders.getData().isEmpty()) {
//				throw new BizException("你所在的部门未设置商务经理，请通知管理员设置后再进行剔除", 10001);
//			}
//			for (Map map : leaders.getData()) {
//				sendBusinessMsg(repository.get(User.class, Long.valueOf(map.get("userid").toString())), currentLoginUser, "SJ_0024", currentLoginUser.getName(), business.getNo());
//			}
            // 剔除商机到部门库
//			business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);
            // 剔除商机到事业部库
            // 2018-10-24 平台资源剔除到X库。
            if (business.getAddTypeCode().equals(BusinessConstant.BUS_ADD_TYPE_CODE_2)) {
                String val = ruleConfigService.getRuleConfigByMap(organizationService.getOrganizationDepartmentId(currentLoginUser.getOrgId()), "GZFL_SYB_BUS_ADD_TYPE_CODE_2");
                if (StringUtils.isNotBlank(val)) {
                    businesslocation = NumberUtils.toInt(val);
                } else {
                    businesslocation = BusinessConstant.BUS_STORE_DEPARTMENT; // 默认事业部库
                }
            } else { // 除开营运资源
                String val = ruleConfigService.getRuleConfigByMap(organizationService.getOrganizationDepartmentId(currentLoginUser.getOrgId()), "GZFL_SYB_BUS_NO_ADD_TYPE_CODE_2");
                if (StringUtils.isNotBlank(val)) {
                    businesslocation = NumberUtils.toInt(val);
                } else {
                    businesslocation = BusinessConstant.BUS_STORE_DEPARTMENT; // 默认事业部库
                }
            }
            business.setBusinessLocation(businesslocation);
            if (business.getBusinessLocation() == BusinessConstant.BUS_STORE_EP) { // 如果是电销库
                BusinessDx bd = businessDxService.get(business.getId());
//            TreeBook treeBook = treeBookService.queryTreeBookByCode("SYS_DX_COUNT");
//            if(NumberUtils.toInt(treeBook.getExt1())<=bd.getBusCount().intValue()){
//				business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
//			}else{
//				business.setBusinessLocation(BusinessConstant.BUS_STORE_GH); //公海库
//			}
                if (null != bd && bd.getBusCount() >= 1) {
                    businesslocation = BusinessConstant.BUS_STORE_GH;
                    // business.setBusinessLocation(BusinessConstant.BUS_STORE_GH); //公海库
                } else {
                    businesslocation = BusinessConstant.BUS_STORE_EP;
                    // business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
                    if (null == bd) {
                        bd = new BusinessDx();
                        bd.setId(business.getId());
                        bd.setBusCount(1);
                    } else {
                        bd.setBusCount(bd.getBusCount() + 1);
                    }
                    repository.saveOrUpdate(bd);
                }

            }
            // 同意剔除
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
            business.setBusinessLocation(businesslocation);
            // 判断当前商机是不是客户的最近商机，是的话就把客户加入到事业部库里面去
            if (business.getBusinessLocation() == BusinessConstant.BUS_STORE_DEPARTMENT) {
                Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == business.getId().longValue()) {
                    // 新增事业部客户数据
                    DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                    if (null == dc) {
                        Map dcMap = new HashMap();
                        dcMap.put("operateUser", currentLoginUser);
                        dcMap.put("businessId", business.getId());
                        dcMap.put("dropUserId", business.getFollowerId());
                        dcMap.put("customerId", business.getCustomerId());
                        dcMap.put("organizationId", business.getBusinessOrganizationId());
                        dcMap.put("dropWay", CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
//					String days = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_GR_11");//隐藏天数获取后台配置
//					days = StringUtils.isBlank(days) ? "0" : days;
//					dcMap.put("lockDays", days);
                        departmentCustomerService.addDepartmentCustomer(dcMap);
                    }
                }
            }
            business.setUpdaterUser(currentLoginUser);
            business.setLoseDeptTime(new Date());
            business.setLastFollowRecordContent("剔除商机。原因：" + content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_DELETE, "剔除商机.原因：" + content, currentLoginUser.getId(), business.getFollowerId(), null,
                    business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
            setBusinessWillDropDate(business);
            repository.saveOrUpdate(business);
        }
    }

    /**
     * 批量特殊剔除商机 电销
     *
     * @param businessIds      商机id集合
     * @param content          剔除原因
     * @param currentLoginUser 操作人
     */
    public void specialDeleteBusiness(String businessIds, String content, User currentLoginUser) {
        Integer businesslocation = BusinessConstant.BUS_STORE_GH;
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要剔除的商机", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入剔除原因", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            // 判断商机是否在个人库，且跟进人为操作人
            if (business.getBusinessLocation() != BusinessConstant.BUS_STORE_EMP) {
                throw new BizException("商机【" + business.getNo() + "】当前状态不能进行剔除", 10001);
            }
            if (business.getFollowerId().longValue() != currentLoginUser.getId()) {
                throw new BizException("你不是商机【" + business.getNo() + "】的跟进人，不能进行剔除", 10001);
            }
            if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())
                    || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus())) {
                // throw new BizException("商机正在做订单处理，不能进行剔除", 10001);
                // 已签单的商机但是在订单那边没有数据，可以剔除
                businesslocation = BusinessConstant.BUS_STORE_DEPARTMENT;
                Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == business.getId().longValue()) {
                    // 新增事业部客户数据
                    DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                    if (null == dc) {
                        Map dcMap = new HashMap();
                        dcMap.put("operateUser", currentLoginUser);
                        dcMap.put("businessId", business.getId());
                        dcMap.put("dropUserId", business.getFollowerId());
                        dcMap.put("customerId", business.getCustomerId());
                        dcMap.put("organizationId", business.getBusinessOrganizationId());
                        dcMap.put("dropWay", CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
//					String days = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_GR_11");//隐藏天数获取后台配置
//					days = StringUtils.isBlank(days) ? "0" : days;
//					dcMap.put("lockDays", days);
                        departmentCustomerService.addDepartmentCustomer(dcMap);
                    }
                }

            }
            // 特殊剔除隐藏三天
//			String days = ruleConfigService.getRuleConfigByMap(0l, "GHK_YCTS_1");
//			Integer hideDays = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 0;
//			business.setLockTime(DateUtil.dateAddDay(new Date(), hideDays));
//			business.setUpdaterUser(currentLoginUser);
            // 剔除商机到公海库
            business.setBusinessLocation(businesslocation);
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_SPECIAL_DELETE);// 特殊剔除
            business.setUpdaterUser(currentLoginUser);
            business.setLockTime(null);
            business.setLoseDeptTime(new Date());
            business.setLastFollowRecordContent("剔除商机。原因：" + content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_SPECIAL_DELETE, "剔除商机.原因：" + content, currentLoginUser.getId(), business.getFollowerId(), null,
                    business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
            setBusinessWillDropDate(business);
            repository.saveOrUpdate(business);
        }
    }

    /**
     * 批量特殊剔除商机到电销库 上门
     *
     * @param businessIds      商机id集合
     * @param content          剔除原因
     * @param currentLoginUser 操作人
     */
    public void smDeleteBusiness(String businessIds, String content, User currentLoginUser) {
        Integer businesslocation = BusinessConstant.BUS_STORE_EP;
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要剔除的商机", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入剔除原因", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            // 判断商机是否在个人库，且跟进人为操作人
            if (business.getBusinessLocation() != BusinessConstant.BUS_STORE_EMP) {
                throw new BizException("商机【" + business.getNo() + "】当前状态不能进行剔除", 10001);
            }
            if (business.getFollowerId().longValue() != currentLoginUser.getId()) {
                throw new BizException("你不是商机【" + business.getNo() + "】的跟进人，不能进行剔除", 10001);
            }
            if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())
                    || BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus())) {
                businesslocation = BusinessConstant.BUS_STORE_DEPARTMENT;
                Customer customer = customerApiService.getCustomerById(business.getCustomerId());
                if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == business.getId().longValue()) {
                    // 新增事业部客户数据
                    DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                    if (null == dc) {
                        Map dcMap = new HashMap();
                        dcMap.put("operateUser", currentLoginUser);
                        dcMap.put("businessId", business.getId());
                        dcMap.put("dropUserId", business.getFollowerId());
                        dcMap.put("customerId", business.getCustomerId());
                        dcMap.put("organizationId", business.getBusinessOrganizationId());
                        dcMap.put("dropWay", CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
//					String days = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_GR_11");//隐藏天数获取后台配置
//					days = StringUtils.isBlank(days) ? "0" : days;
//					dcMap.put("lockDays", days);
                        departmentCustomerService.addDepartmentCustomer(dcMap);
                    }
                }

            }
            // 特殊剔除隐藏三天
//            String days = ruleConfigService.getRuleConfigByMap(0l, "GHK_YCTS_1");
//            Integer hideDays = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 0;
//            business.setLockTime(DateUtil.dateAddDay(new Date(), hideDays));
//            business.setUpdaterUser(currentLoginUser);
            if (!BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus()) && !BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())
                    && !BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus())) {
                BusinessDx bd = businessDxService.get(business.getId());
//            TreeBook treeBook = treeBookService.queryTreeBookByCode("SYS_DX_COUNT");
//            if(NumberUtils.toInt(treeBook.getExt1())<=bd.getBusCount().intValue()){
//				business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
//			}else{
//				business.setBusinessLocation(BusinessConstant.BUS_STORE_GH); //公海库
//			}
                if (null != bd && bd.getBusCount() >= 1) {
                    businesslocation = BusinessConstant.BUS_STORE_GH;
                    // business.setBusinessLocation(BusinessConstant.BUS_STORE_GH); //公海库
                } else {
                    businesslocation = BusinessConstant.BUS_STORE_EP;
                    // business.setBusinessLocation(BusinessConstant.BUS_STORE_EP); //电销库
                    if (null == bd) {
                        bd = new BusinessDx();
                        bd.setId(business.getId());
                        bd.setBusCount(1);
                    } else {
                        bd.setBusCount(bd.getBusCount() + 1);
                    }
                    repository.saveOrUpdate(bd);
                }
            }
            business.setBusinessLocation(businesslocation);
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_SPECIAL_DELETE);// 特殊剔除
            business.setUpdaterUser(currentLoginUser);
            business.setLockTime(null);
            business.setLoseDeptTime(new Date());
            business.setLastFollowRecordContent("剔除商机。原因：" + content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_SPECIAL_DELETE, "剔除商机.原因：" + content, currentLoginUser.getId(), business.getFollowerId(), null,
                    business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
            setBusinessWillDropDate(business);
            repository.saveOrUpdate(business);
        }
    }

    /**
     * 批量隐藏商机
     *
     * @param businessIds      商机id集合
     * @param content          隐藏原因
     * @param currentLoginUser 操作人
     */
    public void updateHideBusiness(String businessIds, String content, User currentLoginUser) {
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要隐藏的商机", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入隐藏原因", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));
            // 判断商机是否在个人库，且跟进人为操作人
            if (business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EMP) {
                throw new BizException("商机【" + business.getNo() + "】当前状态不能进行隐藏", 10001);
            }
            if (business.getFollowerId().longValue() != currentLoginUser.getId()) {
                throw new BizException("你不是商机【" + business.getNo() + "】的跟进人，不能进行隐藏", 10001);
            }
            if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
                throw new BizException("商机正在做订单处理，不能隐藏", 10001);
            }
            // 给部门经理发短信，提醒他进行审核
            Map userMap = new HashMap();
            userMap.put("rootOrgId", currentLoginUser.getOrgId());
//            userMap.put("userRole", "7");//7代表商务经理
            userMap.put("userRoleCodes", "shangwujingli");
            PageData<Map> leaders = userService.searchUser(userMap);
            if (null == leaders || null == leaders.getData() || leaders.getData().isEmpty()) {
                throw new BizException("你所在的部门未设置商务经理，请通知管理员设置后再进行隐藏", 10001);
            }
            for (Map map : leaders.getData()) {
                sendBusinessMsg(repository.get(User.class, Long.valueOf(map.get("userid").toString())), currentLoginUser, "SJ_0013", currentLoginUser.getName(), business.getNo());
            }
            business.setHandleResult(content);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);// 隐藏时把商机所在库改为部门库
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_HIDE);
            business.setUpdaterUser(currentLoginUser);
            business.setLastFollowRecordContent("隐藏商机。原因：" + content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_HIDE, "隐藏商机.原因：" + content, currentLoginUser.getId(), null, null);
            setBusinessWillDropDate(business);
            repository.saveOrUpdate(business);
        }
    }

    /**
     * 审核隐藏商机
     *
     * @param businessId       商机id
     * @param content          审核原因
     * @param result           结果1同意，其他都为驳回
     * @param currentLoginUser 审核人
     */
    public void updateTrialHideBusiness(Long businessId, String content, Integer result, User currentLoginUser) {
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机不存在", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入审核原因", 10001);
        }
        if (!business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_HIDE)) {
            throw new BizException("商机状态已更新，请刷新后再试", 10001);
        }
        String res = "驳回";
        if (1 == result) {// 同意隐藏
            res = "同意隐藏";
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_HIDE_AGREEN);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_DEPARTMENT);// 数据进入事业部库

            // 判断当前商机是不是客户的最近商机，是的话就把客户加入到事业部库里面去
            Customer customer = customerApiService.getCustomerById(business.getCustomerId());
            if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == businessId.longValue()) {
                // 新增事业部客户数据
                DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                if (null == dc) {
                    Map dcMap = new HashMap();
                    dcMap.put("operateUser", currentLoginUser);
                    dcMap.put("businessId", business.getId());
                    dcMap.put("dropUserId", business.getFollowerId());
                    dcMap.put("customerId", business.getCustomerId());
                    dcMap.put("organizationId", business.getBusinessOrganizationId());
                    dcMap.put("dropWay", CustomerRecordConstant.BUS_OPERATE_HIDE_AGREEN);
                    String days = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_GR_11");// 隐藏天数获取后台配置
                    days = StringUtils.isBlank(days) ? "0" : days;
                    dcMap.put("lockDays", days);
                    departmentCustomerService.addDepartmentCustomer(dcMap);
                }
            }

            business.setLastFollowRecordContent("同意隐藏。原因：" + content);
            business.setLoseDeptTime(new Date());
            business.setIsImportant(0);
            business.setIsVip(0);
        } else {
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_HIDE_REJECT);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 数据回到个人库
            business.setLastFollowRecordContent("驳回隐藏。原因：" + content);
        }
        business.setHandleUserId(currentLoginUser.getId());
        business.setUpdaterUser(currentLoginUser);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
        setBusinessWillDropDate(business);
        saveBusinessRecord(business, business.getBusinessOperate(), business.getLastFollowRecordContent(), currentLoginUser.getId(), business.getFollowerId(), null,
                business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
        repository.saveOrUpdate(business);
        sendBusinessMsg(repository.get(User.class, business.getFollowerId()), currentLoginUser, "SJ_0004", business.getNo(), res, content);
    }

    /**
     * 审核剔除商机
     *
     * @param businessId       商机id
     * @param content          审核原因
     * @param result           结果1同意，其他都为驳回
     * @param currentLoginUser 审核人
     */
    public void updateTrialDeleteBusiness(Long businessId, String content, Integer result, User currentLoginUser) {
        Business business = getBusinessById(businessId);
        if (null == business) {
            throw new BizException("商机不存在", 10001);
        }
        if (StringUtils.isBlank(content)) {
            throw new BizException("请输入审核原因", 10001);
        }
        if (!business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_DELETE)) {
            throw new BizException("商机状态已更新，请刷新后再试", 10001);
        }
        String res = "驳回";
        if (1 == result) {// 同意隐藏
            res = "同意剔除";
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_DEPARTMENT);// 数据进入事业部库

            // 判断当前商机是不是客户的最近商机，是的话就把客户加入到事业部库里面去
            Customer customer = customerApiService.getCustomerById(business.getCustomerId());
            if (null != customer.getLastBusId() && customer.getLastBusId().longValue() == businessId.longValue()) {
                // 新增事业部客户数据
                DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(business.getCustomerId());
                if (null == dc) {
                    Map dcMap = new HashMap();
                    dcMap.put("operateUser", currentLoginUser);
                    dcMap.put("businessId", business.getId());
                    dcMap.put("dropUserId", business.getFollowerId());
                    dcMap.put("customerId", business.getCustomerId());
                    dcMap.put("organizationId", business.getBusinessOrganizationId());
                    dcMap.put("dropWay", CustomerRecordConstant.BUS_OPERATE_DELETE_AGREEN);
//					String days = ruleConfigService.getRuleConfigByMap(business.getBusinessOrganizationId(), "GZFL_GR_11");//隐藏天数获取后台配置
//					days = StringUtils.isBlank(days) ? "0" : days;
//					dcMap.put("lockDays", days);
                    departmentCustomerService.addDepartmentCustomer(dcMap);
                }
            }

            business.setLastFollowRecordContent("同意剔除。原因：" + content);
            business.setLoseDeptTime(new Date());
            business.setIsImportant(0);
            business.setIsVip(0);
        } else {
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DELETE_REJECT);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 数据回到个人库
            business.setLastFollowRecordContent("驳回剔除。原因：" + content);
        }
        business.setHandleUserId(currentLoginUser.getId());
        business.setUpdaterUser(currentLoginUser);
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
        setBusinessWillDropDate(business);
        saveBusinessRecord(business, business.getBusinessOperate(), business.getLastFollowRecordContent(), currentLoginUser.getId(), business.getFollowerId(), null,
                business.getFollowerOrganizationId(), null, business.getFollowerName(), "");
        if (1 != result) {
            setBusinessWillDropDate(business);// 剔除驳回计算掉库时间
        }
        repository.saveOrUpdate(business);
        sendBusinessMsg(repository.get(User.class, business.getFollowerId()), currentLoginUser, "SJ_0025", business.getNo(), res, content);
    }

    /**
     * 返无效验证
     *
     * @param businessIds 商机ID 内容
     */
    public void checkInvalidBus(String businessIds, User user) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = this.repository.get(Business.class, Long.parseLong(id));
            if (null != business) {
                if (business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EMP.intValue()) {
                    throw new BizException("商机【" + business.getNo() + "】状态已更新，不能返无效", 10001);
                }
                if (null != business.getIsMind() && business.getIsMind() == 1) {
                    throw new BizException("商机【" + business.getNo() + "】为意向资源，不能返无效", 10001);
                }

                if (business.getFollowerId().intValue() != user.getId().intValue()) {
                    throw new BizException("你不是商机【" + business.getNo() + "】当前跟进人，不能返无效", 10001);
                }
                if (BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(business.getAddTypeCode())) {
                    throw new BizException("商机【" + business.getNo() + "】为自开发，不能返无效", 10001);
                }
                if (CustomerRecordConstant.BUS_OPERATE_DX_CUS_SHARE_PICKUP.equals(business.getBusinessOperate())) {
                    throw new BizException("商机【" + business.getNo() + "】为电销客户共享拾回，不能返无效", 10001);
                }
                if (null != business.getInvalidNumber() && business.getInvalidNumber() >= 2) {
                    throw new BizException("商机【" + business.getNo() + "】返无效超过2次，不能再返无效", 10001);
                }
                if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
                    throw new BizException("商机正在做订单处理，不能返无效", 10001);
                }
            } else {
                throw new BizException("当前商机不存在", 10001);
            }
        }

    }

    /**
     * 返无效
     *
     * @param businessIds 商机ID
     * @param content     内容
     */
    public void saveInvalidBus(String businessIds, String content, User user) {
        String[] ids = businessIds.split(",");
        for (String id : ids) {

            Business business = this.repository.get(Business.class, Long.parseLong(id));
            User outUser = this.userService.getUserById(business.getSingleUserId());// 分单人
            if (null != business) {
                if (business.getBusinessLocation().intValue() != BusinessConstant.BUS_STORE_EMP.intValue()) {
                    throw new BizException("商机【" + business.getNo() + "】状态已更新，不能返无效", 10001);
                }

                if (business.getFollowerId().intValue() != user.getId().intValue()) {
                    throw new BizException("你不是商机【" + business.getNo() + "】当前跟进人，不能返无效", 10001);
                }
                if (BusinessConstant.BUS_ADD_TYPE_CODE_5.equals(business.getAddTypeCode())) {
                    throw new BizException("商机【" + business.getNo() + "】为自开发，不能返无效", 10001);
                }
                if (null != business.getInvalidNumber() && business.getInvalidNumber() >= 2) {
                    throw new BizException("商机【" + business.getNo() + "】返无效超过2次，不能再返无效", 10001);
                }
                if (BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
                    throw new BizException("商机正在做订单处理，不能返无效", 10001);
                }
                business.setInvalidNumber(business.getInvalidNumber() == null ? 1 : (business.getInvalidNumber() + 1));
                business.setLastFollowRecordContent(content);
                business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_INVALID);// 返无效901
                business.setHandleUserId(null);
                business.setBusinessLocation(BusinessConstant.BUS_STORE_ORG);// 部门库
                business.setUpdaterUser(user);
                business.setLastFollowRecordContent(content);
                business.setLastFollowRecordTime(new Date());
                business.setLastFollowRecordUser(user.getName() + user.getLoginName());
                business.setHandleResult(content);
                businessDao.updateByHiber(business);
                saveBusinessInvalidRecord(business, user, CustomerRecordConstant.BUS_OPERATE_INVALID, content, outUser.getName() + outUser.getLoginName(), outUser.getId(),
                        outUser.getOrgId(), business.getFollowerId(), business.getFollowerOrganizationId(), business.getFollowerName());

            } else {
                throw new BizException("当前商机不存在", 10001);
            }
        }

    }

    /**
     * 返无效审核
     *
     * @param businessId 商机ID
     * @param content    内容
     * @param result     判断条件 1 通过
     */
    public void saveAuditBus(Long businessId, String content, Long result, String cost, User currentLoginUser) {
        Business business = this.repository.get(Business.class, businessId);
        User outUser = this.userService.getUserById(business.getSingleUserId());// 分单人
        if (!business.getBusinessOperate().equals(CustomerRecordConstant.BUS_OPERATE_INVALID)) {
            throw new BizException("当前商机未返无效", 10001);
        } else {

            business.setHandleUserId(currentLoginUser.getId());
            String res = "驳回";
            String msg = "商机已进入无效库";
            if (result == 1) {
                business.setLastFollowRecordContent("返无效商机审核通过。原因：" + content);
                business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_INVALID_AGREEN);
                business.setBusinessLocation(BusinessConstant.BUS_STORE_INVALID);// 无效库
                business.setLoseDeptTime(new Date());
                business.setIsImportant(0);
                business.setIsVip(0);
                // 新增反无效数据库的数据
                AntiInvalid ai = new AntiInvalid();
                ai.setId(keyWorker.nextId());
                ai.setCreateUser(currentLoginUser);
                ai.setCustomerId(business.getCustomerId());
                ai.setBusinessId(business.getId());
                ai.setAntiInvalidReason(business.getHandleResult());
                ai.setAntiInvalidReviewerId(currentLoginUser.getId());
                ai.setAntiInvalidReviewerName(currentLoginUser.getName() + currentLoginUser.getLoginName());
                ai.setAntiInvalidUserOrgId(business.getFollowerOrganizationId());
                ai.setAntiInvalidTime(business.getUpdateTime());// 这个更新时间并不是最好的方式，最好是从返无效记录里面去找
                ai.setAntiInvalidUserName(business.getFollowerName());
                ai.setAntiInvalidUserId(business.getFollowerId());
                repository.save(ai);
                res = "通过";
            } else {
                msg = "请在24小时内重新跟进";
                business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_INVALID_REJECT);
                business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
                business.setLastFollowRecordContent("返无效商机审核不通过。原因：" + content);
                setBusinessWillDropDate(business);
            }
            business.setUpdaterUser(currentLoginUser);
            business.setCost(cost);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(currentLoginUser.getName() + currentLoginUser.getLoginName());
            saveBusinessInvalidRecord(business, currentLoginUser, business.getBusinessOperate(), content, outUser.getName() + outUser.getLoginName(), outUser.getId(),
                    outUser.getOrgId(), business.getFollowerId(), business.getFollowerOrganizationId(), business.getFollowerName());
            repository.saveOrUpdate(business);
            sendBusinessMsg(repository.get(User.class, business.getFollowerId()), currentLoginUser, "SJWXJG", business.getNo(), res, msg);
        }

    }

    /**
     * 根据商机的当前操作，计算商机的预计掉库时间
     *
     * @param business 商机
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void setBusinessWillDropDate(Business business) {
        String status = business.getBusinessStatus();// 当前状态
        if (StringUtils.isBlank(status)) {
            business.setWillDropTime(null);
            return;
        }
        if (BusinessConstant.BUS_STATUS_NEW.equals(status)) {// 新增状态的商机不做计算
            business.setWillDropTime(null);
            return;
        }
//		if (BusinessConstant.BUS_STATUS_SIGNED.equals(status)) {//签单状态的商机不做掉库时间计算
//			business.setWillDropTime(null);
//			return;
//		} //2018/4/26去除
        if (business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_DEPARTMENT.intValue()
                || business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_INVALID.intValue()) {// 已进入事业部库或无效库的不做计算
            business.setWillDropTime(null);
            return;
        }
        String op = business.getBusinessOperate();// 当前操作
        Long orgId = business.getBusinessOrganizationId();// 事业部id

        Date now = new Date();// 当前时间
        Date todayDropDate = DateUtil.stringDateToDate(DateUtil.dateToString(now, "yyyy-MM-dd") + " 21:00:00");// 今天掉库执行时间
        Date nextDropDate = DateUtil.stringDateToDate(DateUtil.dateToString(DateUtil.dataAddNumber(now, 5, 1), "yyyy-MM-dd") + " 21:00:00");// 下一次掉库执行时间
        Date minDropDate = null;// 固定一个即将掉库的时间
        try {// 不影响正常的流程
            boolean isVip = (null != business.getIsVip() && business.getIsVip() == 1);
            // 分配首电掉库 GZFL_GR_1 分钟
            if (BusinessConstant.BUS_STATUS_WAIT_FOLLOW.equals(status)
                    && (CustomerRecordConstant.BUS_OPERATE_ALLOT.equals(op) || CustomerRecordConstant.BUS_OPERATE_REFERRAL.equals(op))) {
                String min = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_1");
                if (StringUtils.isNotBlank(min)) {
                    Date callDate = DateUtil.dataAddNumber(business.getDistributionTime(), 12, Integer.valueOf(min));
                    minDropDate = callDate;
                }
            }
            // 上门直接掉二次分配
            if (BusinessConstant.BUS_STATUS_WAIT_FOLLOW.equals(status)
                    && (CustomerRecordConstant.BUS_OPERATE_ALLOT.equals(op) || CustomerRecordConstant.BUS_OPERATE_REFERRAL.equals(op))) {
                String min = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_JL_AGAIN1");
                if (StringUtils.isNotBlank(min)) {
                    Date callDate = DateUtil.dataAddNumber(business.getDistributionTime(), 12, Integer.valueOf(min));
                    minDropDate = callDate;
                }
            }

            // 抢单首电掉库
            if (BusinessConstant.BUS_STATUS_WAIT_FOLLOW.equals(status) && (CustomerRecordConstant.BUS_SING.equals(op))) {
                String min = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_1");
                if (StringUtils.isNotBlank(min)) {
                    Date callDate = DateUtil.dataAddNumber(business.getDistributionTime(), 12, Integer.valueOf(min));
                    minDropDate = callDate;
                }
            }
            // 部门待分配或者部门待抢单
            if (BusinessConstant.BUS_STATUS_DEPT.equals(status) || BusinessConstant.BUS_STATUS_DEPT_SING.equals(status)) {
                String min = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_JL_2");
                if (StringUtils.isNotBlank(min)) {
                    Date callDate = DateUtil.dataAddNumber(business.getDistributionTime(), 12, Integer.valueOf(min));
                    minDropDate = callDate;
                }
            }
            // 剔除
            if (op.equals(CustomerRecordConstant.BUS_OPERATE_DELETE)) {
                String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_JL_3");
                Date d = DateUtil.dataAddNumber(business.getUpdateTime(), 10, Integer.valueOf(hour));
                minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                minDropDate = minDropDate;// 掉库时间
            }
            // 隐藏
            if (op.equals(CustomerRecordConstant.BUS_OPERATE_HIDE)) {
                String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_JL_4");
                Date d = DateUtil.dataAddNumber(business.getUpdateTime(), 10, Integer.valueOf(hour));
                minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                minDropDate = minDropDate;// 掉库时间
            }

            // 剔除驳回
            if (op.equals(CustomerRecordConstant.BUS_OPERATE_DELETE_REJECT)) {
                String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_13");
                Date d = DateUtil.dataAddNumber(business.getUpdateTime(), 10, Integer.valueOf(hour));
                minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                minDropDate = minDropDate;// 掉库时间
            }
            if (op.equals(CustomerRecordConstant.BUS_OPERATE_INVALID_REJECT) || op.equals(CustomerRecordConstant.BUS_OPERATE_HIDE_REJECT)
                    || op.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP)) {
                // 强制移交商务 GZFL_GR_9 小时、隐藏被驳回 GZFL_GR_10 小时、返无效驳回待处理 GZFL_GR_8 小时
                String code = op.equals(CustomerRecordConstant.BUS_OPERATE_INVALID_REJECT) ? "GZFL_GR_8"
                        : op.equals(CustomerRecordConstant.BUS_OPERATE_MOVE_EMP) ? "GZFL_GR_9" : "GZFL_GR_10";
                String hour = ruleConfigService.getRuleConfigByMap(orgId, code);
                if (StringUtils.isNotBlank(hour)) {
                    Date d = DateUtil.dataAddNumber(business.getUpdateTime(), 10, Integer.valueOf(hour));
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                }
            }
            if (op.equals(CustomerRecordConstant.BUS_OPERATE_FOLLOW)) {// 正常跟进
                if (null != business.getNextFollowTime() && status.equals(BusinessConstant.BUS_STATUS_FOLLOWING)
                        && DateUtil.timeBetween(business.getLastFollowTime(), business.getNextFollowTime(), "min") > 0) {// 下一次跟进时间不为空,且状态为跟进中,且最后一次跟进时间小于下一次跟进时间
                    String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_2");// 逾期：GZFL_GR_2 小时
                    if (StringUtils.isNotBlank(hour)) {
                        Date d = DateUtil.dataAddNumber(business.getNextFollowTime(), 10, Integer.valueOf(hour));
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                    }

                    String ishour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_YQ_OTHER12");// 逾期：GZFL_GR_2 小时
                    if (StringUtils.isNotBlank(ishour)
                            && (business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_1) || business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_5))) {
                        Date d = DateUtil.dataAddNumber(business.getNextFollowTime(), 10, Integer.valueOf(ishour));
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                    }

                    String yqhour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_YQ12");// 逾期：GZFL_GR_2 小时
                    if (StringUtils.isNotBlank(yqhour) && (business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_2)
                            || business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_3) || business.getOpportunitytypeCode().equals(BusinessConstant.BUS_OPP_4))) {
                        Date d = DateUtil.dataAddNumber(business.getNextFollowTime(), 10, Integer.valueOf(ishour));
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                    }
                }
            }
            // 根据状态判断
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED)
                    || status.equals(BusinessConstant.BUS_STATUS_ORDER_BACK)) {
                // 正常跟进：接收时间+opportunitytypeCode开发周期，IsVip=0
                // 自开发 GZFL_GR_4 天 二次开发 GZFL_SYB_2 天 公司资源 GZFL_GR_3 天
                String opportunity = business.getOpportunitytypeCode();
                String code = BusinessConstant.BUS_OPP_1.equals(opportunity) || BusinessConstant.BUS_OPP_5.equals(opportunity) ? "GZFL_GR_3"
                        : ((BusinessConstant.BUS_OPP_2.equals(opportunity) || BusinessConstant.BUS_OPP_4.equals(opportunity)) ? "GZFL_SYB_2" : "GZFL_GR_4");
                String days = ruleConfigService.getRuleConfigByMap(orgId, code);
                if (StringUtils.isNotBlank(days)) {
                    Date d = DateUtil.dataAddNumber(business.getDistributionTime(), 5, Integer.valueOf(days) + 1);// 掉库时间需要+1
                    // 时间弄成凌晨4点
                    d = DateUtil.stringDateToDate(DateUtil.dateToString(d, "yyyy-MM-dd") + " 23:00:00");
                    if (DateUtil.timeBetween(todayDropDate, now, "sec") > 0 && DateUtil.timeBetween(d, todayDropDate, "hour") >= 0) {// 预计掉库时间的日期小于等于今天凌晨4点，且当前时间大于今天凌晨4点，则预计掉库时间改为明天早上4:00
                        d = nextDropDate;
                    }
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                }
            }
            // 根据状态判断
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GH_6");
                if (StringUtils.isNotBlank(days)) {
                    Date d = DateUtil.dataAddNumber(business.getDistributionTime(), 5, Integer.valueOf(days) + 1);// 掉库时间需要+1
                    // 时间弄成凌晨4点
                    d = DateUtil.stringDateToDate(DateUtil.dateToString(d, "yyyy-MM-dd") + " 21:00:00");
                    if (DateUtil.timeBetween(todayDropDate, now, "sec") > 0 && DateUtil.timeBetween(d, todayDropDate, "hour") >= 0) {// 预计掉库时间的日期小于等于今天凌晨4点，且当前时间大于今天凌晨4点，则预计掉库时间改为明天早上4:00
                        d = nextDropDate;
                    }
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                }
            }
            if (status.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED) || status.equals(BusinessConstant.BUS_STATUS_ORDER_BACK)) {
                // 已成单：最后一次跟进时间+掉库天数,GZFL_GR_6 天 //已退单：完成时间+掉库天数， GZFL_GR_5
                String code = status.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED) ? "GZFL_GR_6" : "GZFL_GR_5";
                Date date = status.equals(BusinessConstant.BUS_STATUS_ORDER_SUCCESSED) ? business.getLastFollowTime() : business.getFinishTime();
                String days = ruleConfigService.getRuleConfigByMap(orgId, code);
                if (StringUtils.isNotBlank(days)) {
                    Date d = DateUtil.dataAddNumber(date, 5, Integer.valueOf(days) + 1);// 掉库时间需要+1
                    // 时间弄成凌晨4点
                    d = DateUtil.stringDateToDate(DateUtil.dateToString(d, "yyyy-MM-dd") + " 21:00:00");
                    if (DateUtil.timeBetween(todayDropDate, now, "sec") > 0 && DateUtil.timeBetween(d, todayDropDate, "hour") >= 0) {// 预计掉库时间的日期小于等于今天凌晨4点，且当前时间大于今天凌晨4点，则预计掉库时间改为明天早上4:00
                        d = nextDropDate;
                    }
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    minDropDate = isVip ? null : minDropDate;// vip商机不掉库
                }
            }
            /* 电销上门时间计算开始 */
            Map dayMap = new HashMap();
            /* 未连续跟进掉库计算 */
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                // 推广部门的资源 转介绍 自开发 平台营运
                String addTypes[] = {"GZFL_GR_TUIGUANG_LIANXU", "GZFL_GR_ORIGIN_TYPE_8_LIANXU", "GZFL_GR_ORIGIN_TYPE_6_LIANXU", "GZFL_GR_ORIGIN_TYPE_9_LIANXU"};
                String oppCodes[] = {(BusinessConstant.BUS_ADD_TYPE_CODE_1 + "," + BusinessConstant.BUS_ADD_TYPE_CODE_3 + "," + BusinessConstant.BUS_ADD_TYPE_CODE_4),
                        BusinessConstant.BUS_ADD_TYPE_CODE_7, BusinessConstant.BUS_ADD_TYPE_CODE_5, BusinessConstant.BUS_ADD_TYPE_CODE_2};
                for (int i = 0; i < addTypes.length; i++) {
                    if (business.getAddTypeCode().contains(oppCodes[i])) {
                        String addType = addTypes[i];
                        String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                        if (StringUtils.isNotBlank(days)) {
                            dayMap.put("days", NumberUtils.toInt(days) + 1);
                            dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                            String date = workDayDao.queryAfterDate(dayMap);
                            // 时间弄成凌晨4点
                            Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                            minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        }
                    }
                }
            }

            /* 已签单未连续跟进掉库计算 */
            if (status.equals(BusinessConstant.BUS_STATUS_SIGNED) && business.getBusinessLocation() == BusinessConstant.BUS_STORE_EMP) {
                String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_TUIGUANG_LIANXU_ORDER");
                if (StringUtils.isNotBlank(days)) {
                    dayMap.put("days", NumberUtils.toInt(days) + 1);
                    dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                    String date = workDayDao.queryAfterDate(dayMap);
                    // 时间弄成凌晨4点
                    Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                }


            }

            /**电销中心入库资源X天未连续跟进**/
            /* 已签单未连续跟进掉库计算 */
            if (business.getBusinessLocation() == BusinessConstant.BUS_STORE_EMP) {
                String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_ALL_LIANXU");
                if (StringUtils.isNotBlank(days)) {
                    dayMap.put("days", NumberUtils.toInt(days) + 1);
                    dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                    String date = workDayDao.queryAfterDate(dayMap);
                    // 时间弄成凌晨4点
                    Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                }

            }
            /** 电销自开发资源未分配事业部 **/
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                // 推广部门的资源 转介绍 自开发 平台营运
                String addTypes[] = {"GZFL_GH_ORIGIN_TYPE_6"};
                String oppCodes[] = {BusinessConstant.BUS_ORIGIN_TYPE_6};
                for (int i = 0; i < addTypes.length; i++) {
                    if (null != business.getOrigincodeType() && business.getOrigincodeType().equals(oppCodes[i])) { // 自开发
                        String addType = addTypes[i];
                        String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                        if (StringUtils.isNotBlank(days)) {
                            dayMap.put("days", NumberUtils.toInt(days) + 1);
                            dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                            String date = workDayDao.queryAfterDate(dayMap);
                            // 时间弄成凌晨4点
                            Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                            minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        }
                    }
                }
            }
            /** 线索转化的商机 **/
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                // 推广部门的资源 转介绍 自开发 平台营运
                String addTypes[] = {"GZFL_GH_WIDELY"};
                for (int i = 0; i < addTypes.length; i++) {
                    if (null != business.getWidelyType() && business.getWidelyType() == 1) { // 线索转化
                        String addType = addTypes[i];
                        String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                        if (StringUtils.isNotBlank(days)) {
                            dayMap.put("days", NumberUtils.toInt(days) + 1);
                            dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                            String date = workDayDao.queryAfterDate(dayMap);
                            // 时间弄成凌晨4点
                            Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                            minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        }
                    }
                }
            }

            /** 电销拾回的商机 **/
            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                // 推广部门的资源 转介绍 自开发 平台营运
                String addTypes[] = {"GZFL_GH_ORIGIN_TYPE_7"};
                for (int i = 0; i < addTypes.length; i++) {
                    if (null != business.getWayCode()
                            && (business.getWayCode().equals(BusinessConstant.BUS_WAY_CODE_6) || business.getWayCode().equals(BusinessConstant.BUS_WAY_CODE_7))) { // 电销拾回
                        String addType = addTypes[i];
                        String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                        if (StringUtils.isNotBlank(days)) {
                            dayMap.put("days", NumberUtils.toInt(days) + 1);
                            dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                            String date = workDayDao.queryAfterDate(dayMap);
                            // 时间弄成凌晨4点
                            Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                            minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                        }
                    }
                }
            }

            if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                // 各类资源未上门掉库时间计算
                if (null != business.getVisitStatus()) {
                    if (business.getVisitStatus().equals(CustomerRecordConstant.BUS_WAIT_VISIT)) {
                        String addTypes[] = {"GZFL_GR_ORIGIN_TYPE_1_WJK", "GZFL_GR_ORIGIN_TYPE_2_WJK", "GZFL_GR_ORIGIN_TYPE_3_WJK", "GZFL_GR_ORIGIN_TYPE_4_WJK",
                                "GZFL_GR_ORIGIN_TYPE_5_WJK", "GZFL_GR_ORIGIN_TYPE_6_WJK", "GZFL_GR_ORIGIN_TYPE_7_WJK", "GZFL_GR_ORIGIN_TYPE_8_WJK"};
                        String oppCodes[] = {BusinessConstant.BUS_ORIGIN_TYPE_1, BusinessConstant.BUS_ORIGIN_TYPE_2, BusinessConstant.BUS_ORIGIN_TYPE_3,
                                BusinessConstant.BUS_ORIGIN_TYPE_4, BusinessConstant.BUS_ORIGIN_TYPE_5, BusinessConstant.BUS_ORIGIN_TYPE_6, BusinessConstant.BUS_ORIGIN_TYPE_7,
                                BusinessConstant.BUS_ORIGIN_TYPE_8};
                        for (int i = 0; i < addTypes.length; i++) {
                            if (null != business.getOrigincodeType() && business.getOrigincodeType().equals(oppCodes[i])) {
                                String addType = addTypes[i];
                                String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                                if (StringUtils.isNotBlank(days)) {
                                    dayMap.put("days", NumberUtils.toInt(days) + 1);
                                    dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                                    String date = workDayDao.queryAfterDate(dayMap);
                                    // 时间弄成凌晨4点
                                    Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                                }
                            }
                        }

                    }
                }

                // 各类资源未上门未签单时间计算
                if (status.equals(BusinessConstant.BUS_STATUS_FOLLOWING) || status.equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                    String addTypes[] = {"GZFL_GR_ORIGIN_TYPE_1_WQD", "GZFL_GR_ORIGIN_TYPE_2_WQD", "GZFL_GR_ORIGIN_TYPE_3_WQD", "GZFL_GR_ORIGIN_TYPE_4_WQD",
                            "GZFL_GR_ORIGIN_TYPE_5_WQD", "GZFL_GR_ORIGIN_TYPE_6_WQD", "GZFL_GR_ORIGIN_TYPE_7_WQD", "GZFL_GR_ORIGIN_TYPE_8_WQD", "GZFL_GR_ORIGIN_TYPE_9_WQD"};
                    String oppCodes[] = {BusinessConstant.BUS_ORIGIN_TYPE_1, BusinessConstant.BUS_ORIGIN_TYPE_2, BusinessConstant.BUS_ORIGIN_TYPE_3,
                            BusinessConstant.BUS_ORIGIN_TYPE_4, BusinessConstant.BUS_ORIGIN_TYPE_5, BusinessConstant.BUS_ORIGIN_TYPE_6, BusinessConstant.BUS_ORIGIN_TYPE_7,
                            BusinessConstant.BUS_ORIGIN_TYPE_8, BusinessConstant.BUS_ORIGIN_TYPE_9};
                    for (int i = 0; i < addTypes.length; i++) {
                        if (null != business.getOrigincodeType() && business.getOrigincodeType().equals(oppCodes[i])) {
                            String addType = addTypes[i];
                            String days = ruleConfigService.getRuleConfigByMap(orgId, addType);
                            if (StringUtils.isNotBlank(days)) {
                                dayMap.put("days", NumberUtils.toInt(days) + 1);
                                dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                                String date = workDayDao.queryAfterDate(dayMap);
                                // 时间弄成凌晨4点
                                Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                                minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                            }
                        }
                    }
                }

                // VIP未成单掉库
                if (null != business.getIsVip() && business.getIsVip() == 1) {
                    String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_SYB_VIP_1");
                    if (StringUtils.isNotBlank(days)) {
                        dayMap.put("days", NumberUtils.toInt(days) + 1);
                        dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                        String date = workDayDao.queryAfterDate(dayMap);
                        // 时间弄成凌晨4点
                        Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }

                // 90天未连续跟进掉电销库
                if (null != business.getIsVip() && business.getIsVip() == 1 && StringUtils.isNotBlank(business.getOrigincodeType())) {
                    String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_DXGR_6");
                    if (StringUtils.isNotBlank(days)) {
                        dayMap.put("days", NumberUtils.toInt(days) + 1);
                        dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                        String date = workDayDao.queryAfterDate(dayMap);
                        // 时间弄成凌晨4点
                        Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }

                // 自开发资源电销90天未开发意向客户掉库GZFL_GH_ORIGIN_TYPE_6
                if (StringUtils.isNotBlank(business.getOrigincodeType()) && business.getOrigincodeType().equals(BusinessConstant.BUS_ORIGIN_TYPE_6)) {
                    String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_DXGH");
                    if (StringUtils.isNotBlank(days)) {
                        dayMap.put("days", NumberUtils.toInt(days) + 1);
                        dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                        String date = workDayDao.queryAfterDate(dayMap);
                        // 时间弄成凌晨4点
                        Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }
                // 电销中心公海拾回的资源X天未开发出意向掉库
                if (StringUtils.isNotBlank(business.getWayCode()) && business.getWayCode().equals(BusinessConstant.BUS_WAY_CODE_7)) {
                    String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GH_ORIGIN_TYPE_7");
                    if (StringUtils.isNotBlank(days)) {
                        dayMap.put("days", NumberUtils.toInt(days) + 1);
                        dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                        String date = workDayDao.queryAfterDate(dayMap);
                        // 时间弄成凌晨4点
                        Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }

                // 电销中心公海拾回的资源X天未开发出意向掉库
                if (StringUtils.isNotBlank(business.getWayCode()) && business.getWayCode().equals(BusinessConstant.BUS_WAY_CODE_7)) {
                    String days = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_DX_ORIGIN_TYPE_7");
                    if (StringUtils.isNotBlank(days)) {
                        dayMap.put("days", NumberUtils.toInt(days) + 1);
                        dayMap.put("date", DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
                        String date = workDayDao.queryAfterDate(dayMap);
                        // 时间弄成凌晨4点
                        Date d = DateUtil.stringDateToDate(date + " 21:00:00");
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }
            }

            business.setWillDropTime(minDropDate);
        } catch (Exception e) {
            logger.error("计算预计掉库时间出错");
            e.printStackTrace();
        }
    }

    /**
     * 根据商机的当前操作，计算商机的预计流转时间
     *
     * @param business 商机
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void setBusinessWillLzDate(Business business) {
        String status = business.getBusinessStatus();// 当前状态
        String op = business.getBusinessOperate();// 当前操作
        Long orgId = business.getBusinessOrganizationId();// 事业部id

//		Date now = new Date();//当前时间
//		Date todayDropDate = DateUtil.stringDateToDate(DateUtil.dateToString(now, "yyyy-MM-dd") + " 04:00:00");//今天掉库执行时间
//		Date nextDropDate = DateUtil.stringDateToDate(DateUtil.dateToString(DateUtil.dataAddNumber(now, 5, 1), "yyyy-MM-dd") + " 04:00:00");//下一次掉库执行时间
        Date minDropDate = null;// 固定一个即将流转的时间
        try {// 不影响正常的流程

            if (op.equals(CustomerRecordConstant.BUS_OPERATE_FOLLOW)) {// 正常跟进
                if (null != business.getNextFollowTime() && status.equals(BusinessConstant.BUS_STATUS_FOLLOWING)
                        && DateUtil.timeBetween(business.getLastFollowTime(), business.getNextFollowTime(), "min") > 0) {// 下一次跟进时间不为空,且状态为跟进中,且最后一次跟进时间小于下一次跟进时间
                    String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_GR_YQ12");// 逾期：GZFL_GR_YQ12 逾期跟进预计流转时间
                    if (StringUtils.isNotBlank(hour)) {
                        Date d = DateUtil.dataAddNumber(business.getNextFollowTime(), 10, Integer.valueOf(hour));
                        minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                    }
                }
            }

            if (op.equals(CustomerRecordConstant.BUS_OPERATE_LZ_WAIT) && business.getBusinessLocation() == BusinessConstant.BUS_STORE_EMP) {// 流转待处理
                String hour = ruleConfigService.getRuleConfigByMap(orgId, "GZFL_LZ_24");// 逾期：GZFL_GR_YQ12 逾期跟进预计流转时间
                if (StringUtils.isNotBlank(hour)) {
                    Date d = DateUtil.dataAddNumber(new Date(), 10, Integer.valueOf(hour));
                    minDropDate = minDropDate == null ? d : DateUtil.timeBetween(minDropDate, d, "min") > 0 ? minDropDate : d;
                }
            }
            business.setWillProcessedTime(minDropDate);
        } catch (Exception e) {
            logger.error("计算预计流转时间出错");
            e.printStackTrace();
        }
    }

    /**
     * 调用成本 类别计算
     */
    public Map<Object, Object> getTypeCostPrice(Map map) {
        HttpResult result = null;
        String url = ConfigLoader.getConfigLoader().getVaule("cost_price_url").trim();
        try {
            result = httpCon.PostJson(url.trim(), map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("接口调用失败，请稍后再试!", 10001);
        }
        Map mapjson = JsonUtil.json2Obj(result.getData(), Map.class);
        return mapjson;
    }

    /**
     * 调用成本
     */
    public Map<Object, Object> getCostPriceByOriginType(Map map) {
        HttpResult result = null;
        String url = treeBookService.queryTreeBookByCode("cost_price_by_type_url").getExt1();
        try {
            logger.error("getCostPriceByOriginType>>>>>>>>>>" + url);
            logger.error("map>>>>>>>>>>" + map);
            logger.error("JsonUtil>>>>>>>>>>" + JsonUtil.obj2Json(map));
            result = httpCon.PostJson(url.trim(), map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("接口调用失败，请稍后再试!", 10001);
        }
        Map mapjson = JsonUtil.json2Obj(result.getData(), Map.class);
        return mapjson;
    }

    /**
     * 通过业态地区获取事业部id
     */
    public Map<Object, Object> getOrgByCodeType(Map map) {
        HttpResult result = null;
        String url = treeBookService.queryTreeBookByCode("cost_price_by_type_url").getExt1();
        try {
            result = httpCon.PostJson(url.trim(), map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("接口调用失败，请稍后再试!", 10001);
        }
        Map mapjson = JsonUtil.json2Obj(result.getData(), Map.class);
        return mapjson;
    }


    /**
     * 保存从新媒体留言过来的商机
     *
     * @param requestParamMap 参数map
     * @return
     */
    private List<Map> orgxmtList;

    public Long saveAddNewBusinessFromXmt(Map<String, Object> requestParamMap) {
        // 新媒体的资源不再返回失败信息，但是iboss在出现异常时，需要把新媒体传过来的数据记录到日志里面
        try {
            BizExceptionUtil.isException(null == requestParamMap, "参数为空");
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("consultId")), "咨询编号为空");
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("customerName")), "客户名为空");
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("customerPhone")), "客户联系号码为空");
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("businessType")), "咨询类型代码不能为空");// 2018-09-07新增
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("place")), "地区代码为空");
            // BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("sourceUrl")),
            // "来源URL为空");
//				BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("content")), "留言为空");
            BizExceptionUtil.isException(StringUtils.isEmptyObj(requestParamMap.get("web")), "资源所属");
            String sourceUrl = "";
            if (null != requestParamMap.get("sourceUrl")) {
                sourceUrl = requestParamMap.get("sourceUrl").toString();
            } // 来源地址
            String amount = requestParamMap.get("content") + "";// 内容
            String web = requestParamMap.get("web").toString();// 资源所属
            // net.sf.json.JSONObject jsonarray =
            // net.sf.json.JSONObject.fromObject(content);
            // jsonarray.get("bzName")
            // 2018年3月29日 17:18:04 url包含自建站的资源进入待分配。
            // BizExceptionUtil.isException(!sourceUrl.contains("zijianzhan") ,
            // "临时进入待筛选");//2018/4/23 web 新媒体 type 为dk的 进入待分配
            Long loanamount = NumberUtils.toLong(amount.trim());// 原金额
            // 解析贷款金额
            Long yloanamount = null;
            String dkje = "";

            try {
                net.sf.json.JSONObject jsonarray = net.sf.json.JSONObject.fromObject(amount);
                if (null != jsonarray) {
                    DecimalFormat df1 = new DecimalFormat("0.00");
                    Double str = new Double(jsonarray.get("dkje").toString()) * 100;
                    dkje = jsonarray.get("dkje").toString().trim();
                    yloanamount = str.longValue() * 10000;
                }
            } catch (Exception e) {
                dkje = "0";
                yloanamount = 0L;
            }
//                if(loanamount.longValue()>=1000){
//                    loanamount = loanamount.longValue()*100;
//                }else{
//                    loanamount = loanamount.longValue()*1000000;
//                }
//				if(yloanamount.longValue()>=1000){
//					yloanamount = yloanamount.longValue();
//				}else{
//					yloanamount = yloanamount.longValue()*10000;
//				}
            String customerPhone = requestParamMap.get("customerPhone").toString();// 客户号码
            BizExceptionUtil.isException(!StringUtils.isValidMobileNO(customerPhone), "手机号码格式错误");
            String customerName = requestParamMap.get("customerName").toString();// 客户名称
            String place = requestParamMap.get("place").toString();// 地区
            String consultId = requestParamMap.get("consultId").toString();// 咨询编号
            // 2018-08-07 新增咨询类型
            String businessType = StringUtils.isEmptyObj(requestParamMap.get("businessType")) ? "" : requestParamMap.get("businessType").toString();// 咨询类型代码

            String content = "无";
            try {
//            content = StringUtils.isEmptyObj(requestParamMap.get("content")) ? "无": new String(requestParamMap.get("content").toString().getBytes("ISO-8859-1"),"utf-8");// 咨询留言内容
                content = StringUtils.isEmptyObj(requestParamMap.get("content")) ? "无" : requestParamMap.get("content").toString();// 咨询留言内容
//            customerName = new String(customerName.getBytes("ISO-8859-1"),"utf-8");
            } catch (Exception e) {
            }

            // 查询所有事业部CMS_ORG
            if (orgxmtList == null) {
                orgxmtList = treeBookService.queryTreeBookListByCode("CMS_ORG", 1);
            }
            Long organizationId = 161L;// 商机事业部
            String areaV = "全国";
//			place = "WORK_AREA_" + place.toUpperCase();
            // 改为动态新增新媒体过来的表单资源。
            for (Map map : orgxmtList) {
                if (place.equals(map.get("ext4"))) {// 工作区域
                    organizationId = Long.parseLong(map.get("code").toString());// 成都
                    areaV = map.get("ext3").toString();
                }
            }
//				Long organizationId = 161L;//商机事业部
//				String areaV = "全国";
            if (place.equals("cd")) {
                organizationId = 161L;// 成都
                areaV = "四川省/成都市";
            } else if (place.equals("bj")) {
                organizationId = 411L;// 北京
                areaV = "北京市";
            } else if (place.equals("cq")) {
                organizationId = 1410L;
                areaV = "重庆市";
            } else if (place.equals("gz")) {
                organizationId = 841L;
                areaV = "广东省/广州市";
            } else if (place.equals("hz")) {
                organizationId = 4789L;
                areaV = "浙江省/杭州市";
            } else if (place.equals("sz")) {
                organizationId = 522L;
                areaV = "广东省/深圳市";
            } else if (place.equals("wh")) {
                organizationId = 2819L;
                areaV = "湖北省/武汉市";
            } else if ("zz".equalsIgnoreCase(place)) {
                organizationId = 7679856571547131904L;
                areaV = "河南省/郑州市";
            } else if ("fs".equalsIgnoreCase(place)) {
                organizationId = 7682365481751285760L;
                areaV = "广东省/佛山市";
            } else if ("yc".equalsIgnoreCase(place)) {
                organizationId = 7686797379705638912L;
                areaV = "湖北省/宜昌市";
            } else if ("cs".equalsIgnoreCase(place)) {
                organizationId = 7692261072073527296L;
                areaV = "湖南省/长沙市";
            }

            // 商机来源判断2018年1月3日 09:00:49
            String origin_code = (null == requestParamMap.get("web") || StringUtils.isBlank(requestParamMap.get("web").toString())) ? "BUS_LYQD_707"
                    : "BUS_LYQD_" + requestParamMap.get("web").toString().toUpperCase();

            // 非新媒体事业部的资源全部放到待筛选列表中去，这里直接抛出异常通过catch处理就行了
            BizExceptionUtil.isException(("BUS_LYQD_ZY3".equals(origin_code)), "营运资源待筛选");// 资源3
//			BizExceptionUtil.isException((!"BUS_LYQD_XMT".equals(origin_code) && !sourceUrl.contains("zijianzhan")), "网运资源待筛选");
            String originCodeName = "新媒体";
            if (!"BUS_LYQD_707".equals(origin_code)) {
                TreeBook t = treeBookService.queryTreeBookByCode(origin_code);// 验证传入的来源渠道
                if (null == t) {// 如果传入的来源渠道没有找到的话，就默认为新媒体
                    origin_code = "BUS_LYQD_707";

                } else {
                    originCodeName = t.getName();
                }
            }
            User user = repository.get(User.class, 5L);// 直接查找系统中id为5的新媒体管理员用户

            requestParamMap.put("contactWay", "MB");
            requestParamMap.put("areaName", areaV);
            requestParamMap.put("originCodeName", originCodeName);// 名称默认为新媒体
            requestParamMap.put("allot", "0");// 不立即分配

            Business business = new Business();

            business.setCustomerPhone(njCodeUtil.encrypt(customerPhone));// 客户电话
            business.setCustomerName(customerName);// 客户名称
            business.setBusinessOrganizationId(organizationId);// 受理事业部
            business.setOriginCode(origin_code);// 商机来源默认为新媒体
            // businessType 判断业务类型 2018-09-28
            if (businessType.equals("rzdy")) {
                business.setTypeCode("BUS_YT_DYDK");
            } else if (businessType.equals("rzxd")) {
                business.setTypeCode("BUS_YT_XYDK");
            } else {
                businessType = "rzxd";
                business.setTypeCode("BUS_YT_XYDK_1");
            }
            Map newOrgMap = new HashMap();
            newOrgMap.put("placeCode", "BUS_SOR_PLACE_" + place.toUpperCase());
            newOrgMap.put("typeCode", business.getTypeCode());
//			try {
//				Map orgMap = getOrgByCodeType(newOrgMap); //通过业态  地区 获取事业部。
//				if (orgMap.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
//                     business.setBusinessOrganizationId(NumberUtils.toLong(orgMap.get("data").toString()));
//				} else {
//					BizExceptionUtil.isException(1==1, "事业部获取异常");
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
            Map newPriceMap = new HashMap();
            newPriceMap.put("busCode", "BUS_YT_DK");
            newPriceMap.put("placeCode", "BUS_SOR_PLACE_" + place.toUpperCase());
            newPriceMap.put("typeCode", business.getTypeCode());
            newPriceMap.put("type", businessType);
            newPriceMap.put("tel", customerPhone);
            newPriceMap.put("city", place);
            newPriceMap.put("dkje", dkje); // 贷款金额(元)
            newPriceMap.put("web", web);
            try {
                Map priceMap = getTypeCostPrice(newPriceMap);
                Map ob = (Map) priceMap.get("data");
                if (priceMap.get("code").toString().equals("0")) {// 返回结果不为0则分配失败
                    // throw new BizException(priceMap.get("msg").toString(), 10001);
                    business.setIsCost("yes");// 需要计算成本
                    business.setOrigincodeType(ob.get("originType") + ""); // 类别
                    business.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
                } else {
                    business.setOrigincodeType(ob.get("originType") + ""); // 类别
                    business.setCostPrice(NumberUtils.toInt(ob.get("cost") + "")); // 金额
                    business.setIsCost("CBJSFS_NO");// 不需要计算成本
                }
            } catch (Exception e) {
                business.setOrigincodeType(""); // 类别
            }
            business.setBusinessSourceCode("BUS_LYFS_LYZX");// 默认为留言咨询
            // businessType 判断业务类型 2018-09-07
//				if(businessType.equals("rzdy")){
//					business.setTypeCode("BUS_YT_DYDK");
//				}else if(businessType.equals("rzxd")) {
//					business.setTypeCode("BUS_YT_XYDK");
//				}else{
//					businessType = "rzxd";
//					business.setTypeCode("BUS_YT_XYDK_1");
//				}
//				business.setBusinessSourceCode("BUS_LYFS_LYZX");//默认为留言咨询
//					Map map = getOrigincodeType(place.toUpperCase()+"_"+businessType.toUpperCase(),loanamount);
//					if (null != map) {
//						business.setOrigincodeType(map.get("lyqd") + ""); //来源渠道类型
//						business.setCostPrice(NumberUtils.toInt(map.get("amount") + ""));
//					}   //成本最新计算
            business.setWidelyType(3);
            business.setWidelyId(Long.parseLong(consultId));
            business.setSourceAddress(sourceUrl);
            business.setUrl(sourceUrl);// 来源地址同时放入到url字段中
            // 之前的description存现在的remark 现在的content再新加一个字段保存
            if (null != requestParamMap.get("remark")) {
                business.setDescription(String.valueOf(requestParamMap.get("remark")));
            }

            business.setContent(content);
            yloanamount = yloanamount;// 万解析成分
            business.setLoanAmount(yloanamount); // 解析之后的金额
            business.setSourceFlag("1");// 占用第一位外来系统标志表示是从新媒体来的商机
            // TODO 客户需求待定
            // business.setLoanAmount(loanamount);
//        business.setLoanCycle();
//        business.setLoanInterrestRate();
//        business.setLoadInterrestValue();
//        business.setLoanTime();
            // 新建类型默认为新媒体
             TreeBook tb = treeBookService.queryTreeBookByCode("AUTO_OPEN");
             if(null!=tb&&tb.getStatus()==1){
                 business.setBusinessStatus(BusinessConstant.BUS_STATUS_AUTO_NEW);//待自动分配
             }
            return saveAddNewBusiness(requestParamMap, business, user, BusinessConstant.BUS_ADD_TYPE_CODE_4);
        } catch (Exception e) {
            // 记录失败日志
            e.printStackTrace();
            SourceBusiness sb = new SourceBusiness();
            sb.setId(keyWorker.nextId());
            sb.setCreaterId(1L);
            sb.setCreaterName("iboss系统");
            sb.setCreateTime(new Date());
            if (null != requestParamMap.get("customerName")) {
                sb.setCustomerName(String.valueOf(requestParamMap.get("customerName")));
            }
            if (null != requestParamMap.get("customerPhone")) {

                sb.setCustomerPhone(String.valueOf(requestParamMap.get("customerPhone")));
                sb.setCustomerPhoneBak(sb.getCustomerPhone());
                sb.setCustomerPhone(njCodeUtil.encrypt(sb.getCustomerPhone()));
            }
            if (null != requestParamMap.get("content")) {
                sb.setContent(String.valueOf(requestParamMap.get("content")));
            }
            if (null != requestParamMap.get("consultId")) {
                sb.setConsultId(String.valueOf(requestParamMap.get("consultId")));
            }
            if (null != requestParamMap.get("businessType")) {
                sb.setBusinessType(String.valueOf(requestParamMap.get("businessType")));
            }
            if (null != requestParamMap.get("place")) {
                sb.setPlace(String.valueOf(requestParamMap.get("place")));
            }
            if (null != requestParamMap.get("web")) {
                sb.setWeb(String.valueOf(requestParamMap.get("web")));
            }
            if (null != requestParamMap.get("sourceUrl")) {
                sb.setSourceUrl(String.valueOf(requestParamMap.get("sourceUrl")));
            }

            sb.setStatus(0);
            String err = e.getMessage();
            logger.error("xmtadd>>>>>>>>>>>>>>>>>>>>>" + err);
            err = err.length() > 512 ? e.getMessage().substring(0, 512) : err;
            sb.setErrorMsg(err);
            repository.save(sb);
            return -1L;
        }

    }

    /**
     * 根据金额设置资源类型 来源渠道类型
     */
    private Map<String, String> getOrigincodeType(String code, Long amount) {
        Map map = new HashMap();
        TreeBook book = treeBookService.queryTreeBookByCode(code);
        if (null != book && book.getStatus() == 1) {
            if (amount.longValue() < 5000000) {
                map.put("lyqd", "ORIGIN_TYPE_4");
                map.put("amount", book.getExt2());
                return map;
            } else if (amount.longValue() >= 5000000 && amount.longValue() < 20000000) {
                map.put("lyqd", "ORIGIN_TYPE_1");
                map.put("amount", book.getExt3());
                return map;
            } else if (amount.longValue() >= 20000000 && amount.longValue() < 50000000) {
                map.put("lyqd", "ORIGIN_TYPE_5");
                map.put("amount", book.getExt4());
                return map;
            } else if (amount.longValue() >= 50000000) {
                map.put("lyqd", "ORIGIN_TYPE_3");
                map.put("amount", book.getExt4());
                return map;
            } else {
                map.put("lyqd", "ORIGIN_TYPE_4");
                map.put("amount", book.getExt2());
                return map;
            }

        } else {
            map.put("lyqd", "ORIGIN_TYPE_4");
            map.put("amount", 0);
            return map;
        }

    }

    /**
     * 根据地区 业态 来源渠道类型选择成本 dq 地区 yt 业态 origincodeType 来源渠道类型
     */
    private Long getCosts(String dq, String yt, String origincodeType) {
        Long cost = 0l;
        TreeBook tb = treeBookService.queryTreeBookByCode(dq);
        if (null != tb && tb.getStatus() == 1) {
            TreeBook rztb = null;
            if (yt.contains("BUS_YT_XYDK")) {
                rztb = treeBookService.queryTreeBookByCode(tb.getExt4().trim().toUpperCase() + "_RZXD");
                if (null != rztb && rztb.getStatus() == 1) {
                    if (BusinessConstant.BUS_ORIGIN_TYPE_4.equals(origincodeType)) {// 如果是二类资源
                        cost = NumberUtils.toLong(rztb.getExt2());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_1.equals(origincodeType)) { // 3类
                        cost = NumberUtils.toLong(rztb.getExt3());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_5.equals(origincodeType)) { // 4类
                        cost = NumberUtils.toLong(rztb.getExt4());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_3.equals(origincodeType)) { // 5类
                        cost = NumberUtils.toLong(rztb.getExt5());
                    }
                    return cost;
                }
            } else if (yt.contains("BUS_YT_DYDK")) {
                rztb = treeBookService.queryTreeBookByCode(tb.getExt4().trim().toUpperCase() + "_RZDY");
                if (null != rztb && rztb.getStatus() == 1) {
                    if (BusinessConstant.BUS_ORIGIN_TYPE_4.equals(origincodeType)) {// 如果是二类资源
                        cost = NumberUtils.toLong(rztb.getExt2());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_1.equals(origincodeType)) { // 3类
                        cost = NumberUtils.toLong(rztb.getExt3());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_5.equals(origincodeType)) { // 4类
                        cost = NumberUtils.toLong(rztb.getExt4());
                    } else if (BusinessConstant.BUS_ORIGIN_TYPE_3.equals(origincodeType)) { // 5类
                        cost = NumberUtils.toLong(rztb.getExt5());
                    }
                    return cost;
                }
            } else {
                return cost;
            }
        }
        return cost;
    }

    /**
     * 设置重点商机
     *
     * @param ids              商机集合
     * @param currentLoginUser 操作人
     * @param isImportant      设置类型 1重点，其他不为重点
     */
    public void setImportant(String ids, User currentLoginUser, String isImportant) {
        BizExceptionUtil.isException(StringUtils.isEmpty(ids), "请传入需要设置的商机");
        String[] arryIds = ids.split("\\|");
        Integer isi = "1".equals(isImportant) ? 1 : 0;
        for (int i = 0; i < arryIds.length; i++) {
            Business business = getBusinessById(Long.parseLong(arryIds[i]));
            BizExceptionUtil.isException((null == business || null == business.getFollowerId() || BusinessConstant.BUS_STORE_EMP.intValue() != business.getBusinessLocation()),
                    "商机不存在或状态已更新，不能进行设置");
            BizExceptionUtil.isException((null == business.getFollowerId() || business.getFollowerId().longValue() != currentLoginUser.getId().longValue()),
                    "商机【" + business.getNo() + "】不是你的商机，不能进行设置");
            business.setIsImportant(isi);
            business.setUpdaterUser(currentLoginUser);
            repository.saveOrUpdate(business);
        }
    }

    public Business getBusinessByNo(String businessNo) {
        return repository.findUniqueByProperty(Business.class, "no", businessNo);
    }

    /**
     * 更新商机的首电时间以及状态。打电话时使用
     *
     * @param business 商机
     * @param user     用户
     */
    public void saveBusinessCallRemark(Business business, User user) {
        if (null != business.getFollowerId() && user.getId().longValue() == business.getFollowerId().longValue()
                && business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EMP.intValue()) {
            // 更新商机的当前操作
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_FOLLOW);
            business.setLastFollowTime(new Date());

            // 判断商机是否待跟进，是的话改为跟进中
            if (business.getBusinessStatus().equals(BusinessConstant.BUS_STATUS_WAIT_FOLLOW)) {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
            }
            // 判断商机第一次跟进时间是否为空，是的话该为当前时间
            if (null == business.getFirstFollowTime()) {
                business.setFirstFollowTime(new Date());
            }

            // 商机跟进次数+1，计算最近的掉库时间
            Integer times = business.getFollowTimes() == null ? 1 : business.getFollowTimes() + 1;
            business.setFollowTimes(times);
            business.setUpdaterUser(user);

            // 写入首电时间
            if (null == business.getFirstCallTime()) {
                business.setFirstCallTime(new Date());
                business.setBusinessStage(BusinessConstant.BUS_NEXT_FOLLOW_STAGE_CODE_0);
            }

            setBusinessWillDropDate(business);
            setBusinessWillLzDate(business);
        }
        if (business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_GH) {
            // 公海库，隐藏天数,公共方法
            /*
             * String days = ruleConfigService.getRuleConfigByMap(0l, "GHK_YCTS_1"); Integer
             * hideDays = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 0; Date
             * lockTime; lockTime = null != business.getLockTime() ? business.getLockTime()
             * : new Date();
             */
            business.setLastCallTime(new Date());
            business.setUpdaterUser(user);
        }
        // 更新最后一次备注信息
        business.setLastFollowRecordContent("打电话");
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        repository.saveOrUpdate(business);
    }

    /**
     * 删除已选的商机产品关联信息
     *
     * @param productId        产品id
     * @param businessId       商机id
     * @param currentLoginUser 操作人
     */
    public void deleteBusinessProduct(Long productId, Long businessId, User currentLoginUser) {
        Business business = this.repository.get(Business.class, businessId);
        BizExceptionUtil.isException(null == business, "商机不存在");
        if (null != business.getFollowerId() && currentLoginUser.getId().longValue() == business.getFollowerId().longValue()
                && business.getBusinessLocation().intValue() == BusinessConstant.BUS_STORE_EMP.intValue()) {
            // 先删除已有的产品信息
            Map map = new HashMap();
            map.put("businessId", businessId);
            map.put("productId", productId);
            businessDao.deleteBusinessProductByMap(map);
        } else {
            throw new BizException("你无权删除商机关联的产品，请刷新页面再试", 10001);
        }

    }

    /**
     * 资源端批量新增商机
     *
     * @param data    页面传入的vo
     * @param user    新增人
     * @param addType 新增类型
     * @param allot   1、立即分配
     * @return
     */
    public void saveAddBatchNewBusiness(BusinessAddVo data, User user, String addType, Integer allot) {
        // 验证、组装传入的数据
        BizExceptionUtil.isException(null == data, "传入了空信息，无法新增");
        Customer customer = data.getCustomer();
        BizExceptionUtil.isException(null == customer, "客户信息为空，无法新增");
        BizExceptionUtil.isException(StringUtils.isEmpty(customer.getCustomerPhone()), "客户信息联系号码为空，无法新增");
        BizExceptionUtil.isException(StringUtils.isEmpty(customer.getContactWay()), "客户信息联系类型为空，无法新增");

        Business business = data.getBusiness();
        BizExceptionUtil.isException(null == business, "客户【" + customer.getCustomerPhone() + "】商机信息为空，无法新增");
        BizExceptionUtil.isException(StringUtils.isEmpty(business.getProvince()), "客户【" + customer.getCustomerPhone() + "】商机业务区域为空，无法新增");
        BizExceptionUtil.isException(null == business.getBusinessOrganizationId(), "客户【" + customer.getCustomerPhone() + "】商机未选择受理事业部，无法新增");
        BizExceptionUtil.isException(StringUtils.isEmpty(business.getTypeCode()), "客户【" + customer.getCustomerPhone() + "】商机未选择业态，无法新增");

        List<Contact> contacts = data.getContacts();
        BizExceptionUtil.isException(null == contacts || contacts.isEmpty(), "客户【" + customer.getCustomerPhone() + "】联系人为空，无法新增");

        // 客户联系人判重
        for (Contact contact : contacts) {
            BizExceptionUtil.isException(StringUtils.isEmpty(contact.getName()), "客户【" + customer.getCustomerPhone() + "】有联系人未填写名称，无法新增");
            BizExceptionUtil.isException(StringUtils.isEmpty(contact.getNo()), "客户【" + customer.getCustomerPhone() + "】有联系人未填写号码，无法新增");
            String status = contact.getStatus();
            String name = contact.getName();

            if (null != contact.getId()) {
                contact = repository.get(Contact.class, contact.getId());
                BizExceptionUtil.isException(
                        null == contact || null == customer.getId() || null == contact.getCustomerId() || contact.getCustomerId().longValue() != customer.getId().longValue(),
                        "客户【" + customer.getCustomerPhone() + "】联系人【" + contact.getName() + "】信息异常，无法新增");
                contact.setName(name);
                // 除了设为主联系人外，其他的状态都不变
                if (CustomerConstant.CUS_CONTACT_STATUS_2.equals(status)) {
                    contact.setStatus(CustomerConstant.CUS_CONTACT_STATUS_2);
                }
            } else {// 客户联系人判重
                contact.setNo(njCodeUtil.encrypt(contact.getNo()));
                Map c = new HashMap();
                c.put("contactWay", contact.getContactWay());
                c.put("customerNumber", contact.getNo());
                Integer count = contactDao.queryContactCountForJudgeRepeat(c);
                BizExceptionUtil.isException(count > 0, "客户【" + customer.getCustomerPhone() + "】联系人【" + contact.getName() + "】号码已存在，无法新增");
            }
        }
        // 调用单个保存商机的方法进行保存
        Map requestMap = new HashMap();
        requestMap.put("areaName", business.getProvince());
        requestMap.put("contactWay", customer.getContactWay());
        requestMap.put("age", customer.getAge());
        requestMap.put("address", customer.getAddress());
        requestMap.put("registeredResidence", customer.getRegisteredResidence());
        requestMap.put("email", customer.getEmail());
        requestMap.put("maritalStatus", customer.getMaritalStatus());
        requestMap.put("birthday", customer.getBirthday());
        requestMap.put("idCard", customer.getIdCard());
        requestMap.put("sex", customer.getSex());
        requestMap.put("eduBackground", customer.getEduBackground());
        requestMap.put("originCodeName", customer.getOriginName());
        requestMap.put("customerAttr", data.getCusAttrVo());
        requestMap.put("contacts", contacts);
        requestMap.put("allot", allot);
        requestMap.put("productIdsTemp", business.getLastFollowRecordContent());// 页面用了最后一次跟进记录来记录选中的产品id，这里放入map后，要把跟进记录清空
        String customerPhone = business.getCustomerPhone();
        customerPhone = njCodeUtil.encrypt(customerPhone);
        business.setCustomerPhone(customerPhone);
        business.setLastFollowRecordContent("");
        saveAddNewBusiness(requestMap, business, user, addType);
    }

    public void updateBusinessTransferUser(User user, String ids, String userId) {
        try {
            User toUser = userService.getUserById(Long.valueOf(userId));
            if (StringUtils.isNotBlank(ids)) {
                String[] strings = ids.split(",");
                for (String str : strings) {
                    Map recordMap = new HashMap();
                    Business business = getBusinessById(Long.valueOf(str));
                    User lUser = userService.getUserById(business.getCreaterId());
                    recordMap.put("tableName", Business.TABLE_NAME);
                    recordMap.put("tableId", business.getId());
                    recordMap.put("recordType", "BUS_TRUNOVER_1");
                    recordMap.put("operateUser", user.getId());
                    recordMap.put("cusId", business.getCustomerId());
                    recordMap.put("fromUserId", lUser.getId());
                    recordMap.put("fromUserOrgId", lUser.getOrgId());
                    recordMap.put("toUserId", toUser.getId());
                    recordMap.put("toUserOrgId", toUser.getOrgId());
                    recordMap.put("content", "移交了商机");

                    business.setCreateUser(toUser);
                    business.setCreaterName(toUser.getName());
                    business.setCreaterId(toUser.getId());
                    business.setCreaterOrgId(toUser.getOrgId());
                    businessDao.updateByHiber(business);
                    customerRecordService.saveCustomerRecord(recordMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量移交待处理商机异常：" + e.getMessage());
            throw new BizException("批量移交待处理商机异常:" + e.getMessage(), 10006);
        }
    }

    public void updateBusinessGroup(String businessIds, String groupId, User user) {
        try {
            Business business = null;
            if (StringUtils.isNotBlank(businessIds)) {
                for (String businessId : businessIds.split(",")) {
                    business = this.getBusinessById(Long.parseLong(businessId));
                    business.setGroupId(Long.parseLong(groupId));
                    business.setUpdaterUser(user);
                    businessDao.updateByHiber(business);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量移动商机分组异常：" + e.getMessage());
            throw new BizException("批量移动商机分组异常：" + e.getMessage(), 10006);
        }

    }

    /**
     * 保存商机自动分配回调异常信息
     *
     * @param error
     */
    public void saveAllotErrorInfo(Map error) {
        error.put("id", keyWorker.nextId());
        error.put("createTime", DateUtil.dateToString(new Date()));
        businessDao.addBusinessAllotError(error);
    }

    /**
     * 获取用户所在部门及子部门的id集合字符串，以逗号分割
     *
     * @return id集合字符串
     */
    public String getUserOrganizationIds(Long orgId) {
        return organizationService.getOrgIdsByParentOrgId(orgId);
    }

    public List<Map> listReferralByMap(Map map) {
        return businessDao.listReferralByMap(map);
    }

    public Integer countCostRecordByMap(Map map) {
        return businessDao.countCostRecordByMap(map);
    }

    public List<Map> listCostRecordByMap(Map map) {
        return businessDao.listCostRecordByMap(map);
    }

    public Long countCost(Map map) {
        return businessDao.countCost(map);
    }

    public List<Map> countSignBusinessByMap(Map map) {
        return businessDao.countSignBusinessByMap(map);
    }

    /**
     * 流转分配商机
     *
     * @param businessIds 商机id集合
     * @param allotUser   分配人
     * @param receiverId  被分配人
     */
    public void allotLzBusiness(String businessIds, User allotUser, Long receiverId) {
        if (StringUtils.isBlank(businessIds)) {
            throw new BizException("请选择要分配的商机", 10001);
        }
        String[] ids = businessIds.split(",");
        for (String id : ids) {
            Business business = getBusinessById(Long.valueOf(id));

            if (null == business
                    || (!business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_EMP) && !business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_ORG))) {
                throw new BizException("商机不存在或已掉库，请查询后再试", 10001);
            }

            User ruser = null;
            if (null != receiverId) {
                ruser = repository.get(User.class, receiverId);
                if (null == ruser) {
                    throw new BizException("接收人不存在，不能分配商机", 10001);
                }
            }
            business.setDistributionTime(new Date());// 本次分配时间
            business.setFollowerName(ruser.getName() + ruser.getLoginName());
            business.setFollowerId(ruser.getId());
            business.setFollowerOrganizationId(ruser.getOrgId());
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_LZ_WAIT);
            business.setWayCode(BusinessConstant.BUS_WAY_CODE_5);// 流转分配
            business.setFollowTimes(0);
            business.setIsVip(0);
            business.setIsImportant(0);
            business.setOverdueFollowNum(0);
            business.setLzProcessedTime(new Date());

            String content = "流转分配商机给【" + ruser.getName() + ruser.getLoginName() + "】";
            // 将分配操作写在最后一次备注上
            business.setLastFollowRecordContent(content);
            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(allotUser.getName() + allotUser.getLoginName());
            // 写上新增备注，发送短信通知
            saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_LZ_ALLOT, content, allotUser.getId(), null, business.getFollowerId(), null,
                    business.getFollowerOrganizationId(), "", business.getFollowerName());
            sendBusinessMsg(ruser, allotUser, "SJ_0030", allotUser.getName(), business.getNo());
            // 设置预计流转时间
            setBusinessWillLzDate(business);

            business.setUpdaterUser(allotUser);
            repository.saveOrUpdate(business);
        }

    }

    public boolean dropDxk(Business business, Integer dropCode, User user) {
        boolean temp = true;
        try {

            business.setBusinessLocation(BusinessConstant.BUS_STORE_EP);// 电销库

            business.setLastFollowRecordUser(user.getName() + user.getLoginName());
            Map recordMap = new HashMap();
            String content = "";
            if (0 == dropCode) {
                business.setBusinessOperate(CustomerRecordConstant.BUS_OUT_DP_0);
                recordMap.put("recordType", CustomerRecordConstant.BUS_OUT_DP_0);
                content = "电销掉库_商务主动剔除";
            } else if (1 == dropCode) {
                business.setBusinessOperate(CustomerRecordConstant.BUS_OUT_DP_1);
                recordMap.put("recordType", CustomerRecordConstant.BUS_OUT_DP_1);
                content = "电销掉库_指定天数内未上门";
            } else if (2 == dropCode) {
                business.setBusinessOperate(CustomerRecordConstant.BUS_OUT_DP_2);
                recordMap.put("recordType", CustomerRecordConstant.BUS_OUT_DP_2);
                content = "电销掉库_上门后，指定天数内未签单";
            } else if (3 == dropCode) {
                business.setBusinessOperate(CustomerRecordConstant.BUS_OUT_DP_3);
                recordMap.put("recordType", CustomerRecordConstant.BUS_OUT_DP_3);
                content = "电销掉库_签单后，指定天数内未跟进";
            }
            business.setLastFollowRecordContent(content);
            business.setLoseDeptTime(new Date());
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_DP_DROP);
            business.setUpdaterUser(user);
            repository.saveOrUpdate(business);

            recordMap.put("tableName", Business.TABLE_NAME);
            recordMap.put("tableId", business.getId());
            recordMap.put("cusId", business.getCustomerId());
            recordMap.put("content", content);
            recordMap.put("fromUserId", business.getFollowerId());// 旧跟进人新的跟进人
            recordMap.put("operateUser", user.getId());
            recordMap.put("ext1", business.getBusinessStage());// 商机所在库
            recordMap.put("ext2", business.getBusinessLocation());// 商机当前阶段
            recordMap.put("ext4", business.getBusinessStatus());// 商机当前状态
            recordMap.put("ext3", business.getNo());// 商机编号
            recordMap.put("ext5", dropCode);// 附件id
            recordMap.put("fromUserOrgId", business.getFollowerOrganizationId());// 出库人部门id
            customerRecordService.saveCustomerRecord(recordMap);
            // String date = DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm");

            // sendBusinessMsg(user, null, "SJ_0002",
            // business.getFollowerName(),business.getNo(),business.getLastFollowRecordContent(),date,"1");
        } catch (Exception e) {
            temp = false;
            throw new BizException("掉库异常：" + e.getMessage(), 10006);

        } finally {
            return temp;
        }
    }

    public void pickUpBusiness(Long businessId, User user, Integer type) {

        if (null != user.getDisableCutoffTime() && user.getDisableCutoffTime().getTime() > new Date().getTime()) {
            throw new BizException("商务在" + DateUtil.dateToString(user.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，无法拾回商机", 10001);
        }

        UserSetting userSetting = this.repository.get(UserSetting.class, user.getId());
        if (null != userSetting && null != userSetting.getIsPickUp() && 0 == userSetting.getIsPickUp()) {
            throw new BizException("商务拾回功能没有开启，无法拾回商机", 10001);
        }

        BizExceptionUtil.isException(null == businessId, "商机不存在");
        Business business = this.repository.get(Business.class, businessId);
        BizExceptionUtil.isException(null == business, "商机不存在");
        // 判断库容量是否已经满了，满了则不能接单
        Map numMap = new HashMap();
        numMap.put("followerId", user.getId());
        isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(user.getOrgId()));
        /*
         * Map existed = new HashMap(); existed.put("customerId",
         * business.getCustomerId()); existed.put("businessLocation",
         * String.valueOf(BusinessConstant.BUS_STORE_EMP + "," +
         * BusinessConstant.BUS_STORE_REFERRAl+","+BusinessConstant.BUS_STORE_SOURCE));
         * existed.put("notInBusinessStatus", "'" +
         * BusinessConstant.BUS_STATUS_ORDER_SUCCESSED + "','" +
         * BusinessConstant.BUS_STATUS_ORDER_BACK + "'");
         *
         * List<Map> list = businessDao.listBusinessByMap(existed);
         *
         * if(null != list && list.size()>0){ throw new BizException("商机不能拾回!", 10001);
         * }
         */
        if (null != business.getLockTime() && business.getLockTime().getTime() > new Date().getTime()) {
            throw new BizException("商机已经被隐藏，不能拾回!", 10001);
        }

        if (!business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_GH) && !business.getBusinessLocation().equals(BusinessConstant.BUS_STORE_EP)) {
            throw new BizException("商机已经被拾回!", 10001);
        }

        // business.setDistributionTime(new Date());//本次分配时间
        business.setFollowerName(user.getName() + user.getLoginName());
        business.setFollowerId(user.getId());
        business.setFollowerOrganizationId(user.getOrgId());
        if (!BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
            if (BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())) {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_SIGNED);
            } else {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
            }
        }
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);// 个人库
        business.setDistributionTime(new Date());
        business.setVisitStatus(null);
        business.setLastCallTime(null);
        business.setLockTime(null);
        business.setLastFollowTime(new Date());

        String content = "";
        String recordType = "";
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);// 拾回
        if (1 == type) {
            recordType = CustomerRecordConstant.BUS_DXK_PICKUP;// 拾回商机
            business.setBusTypeDx(CustomerRecordConstant.BUS_OUT_DX);// 公海库拾回标示安电销移交资源掉库
            content = "电销库拾回商机";

        } else if (2 == type) {
            recordType = CustomerRecordConstant.BUS_PICKUP;// 拾回商机
            content = "公海库拾回商机";
        }
        // business.setOrigincodeType(BusinessConstant.ORIGIN_TYPE_7);//来源渠道方式-拾回
        if (null != user.getOrgId()) {
            business.setBusinessOrganizationId(organizationService.getOrganizationDepartmentId(user.getOrgId()));// 所属事业部
        }
        business.setBusinessOperate(recordType);// 拾回商机
        business.setLastFollowRecordContent(content);
        business.setLastFollowRecordTime(new Date());

        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setUpdaterUser(user);
        this.repository.saveOrUpdate(business);
        setBusinessWillDropDate(business);
        // 写上新增备注，发送短信通知
        saveBusinessRecord(business, recordType, content, user.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());
    }

    /**
     * 拾回自跟进
     *
     * @param id
     * @return 返回拾回后的商机状态
     */

    public String pickUpToFollow(Long id, User user) {
        Business business = this.repository.get(Business.class, id);
        BizExceptionUtil.isException(null == business, "商机不存在");
        if (null != user.getDisableCutoffTime() && user.getDisableCutoffTime().getTime() > new Date().getTime()) {
            throw new BizException("商务在" + DateUtil.dateToString(user.getDisableCutoffTime(), "yyyy-MM-dd HH:mm:ss") + "之前处于被禁用状态，无法拾回商机", 10001);
        }

        UserSetting userSetting = this.repository.get(UserSetting.class, user.getId());
        if (null != userSetting && null != userSetting.getIsPickUp() && 0 == userSetting.getIsPickUp()) {
            throw new BizException("商务拾回功能没有开启，无法拾回商机", 10001);
        }

        Integer location = business.getBusinessLocation();
        // 判断哪些库可以拾回 除开资源库、个人库、部门库、转介绍库，商机都可以拾回
        if (BusinessConstant.BUS_STORE_SOURCE.equals(location) || BusinessConstant.BUS_STORE_EMP.equals(location) || BusinessConstant.BUS_STORE_ORG.equals(location)
                || BusinessConstant.BUS_STORE_REFERRAl.equals(location) || BusinessConstant.BUS_STORE_FQ.equals(location)) {
            throw new BizException("商机当前所在库不能拾回！", 10001);
        }
        // 更改事业部
        BizExceptionUtil.isException(null == user.getOrgId(), "你还未设置资源部门，请联系管理员进行设置！");
        Long deptId = organizationService.getOrganizationDepartmentId(user.getOrgId());
        BizExceptionUtil.isException(-1 == deptId, "未找到你当前所在事业部，请联系管理员进行设置！");

        // 判断库容量是否已经满了，满了则不能接单
        Map numMap = new HashMap();
        numMap.put("followerId", user.getId());
        isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(user.getOrgId()));

        if (null != user.getOrgId()) {
            business.setBusinessOrganizationId(deptId);// 所属事业部
        }

        // 最新修改人、获取方式、计算成本改为CBJSFS_NO, 跟进次数清零。
        business.setUpdaterUser(user);
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);
        // business.setIsCost("CBJSFS_NO");
        business.setFollowTimes(0);
        // 已签单的状态不变，已退单的状态改为已签单，其他的状态都改成跟进中 2018年6月6日 10:43:27

        if (!BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
            if (BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())) {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_SIGNED);
            } else {
                business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
            }
        }

        // opportunitytypeCode 为 COMMON_OPP_SH 最新分配时间 lastFollowTime lastLoseTime清空
        // lastLoseType清空 groupId清空 vip为0
        // business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_4);
        business.setLoseDeptTime(null);
        business.setNextFollowTime(null);
        business.setNextFollowContent(null);
        business.setBusinessStage(null);
        business.setGroupId(null);
        business.setIsVip(0);
        // 最后一次备注人名称 最后一次备注时间 最后一次备注记录内容
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setLastFollowTime(new Date());
        business.setLastFollowRecordContent("拾回自跟进");
        business.setLastFollowRecordTime(new Date());
        // 更新跟进人相关信息
        business.setBusinessOperate(CustomerRecordConstant.BUS_GR_PICKUP);
        business.setFollowerId(user.getId());
        business.setFollowerName(user.getName() + user.getLoginName());
        business.setFollowerOrganizationId(user.getOrgId());
        business.setDistributionTime(new Date());

        // 如果是转介绍商机 查询配置 配置内为转介绍 外是自开发商机 转介绍为0，
        if (null != business.getIsReferral() && Integer.valueOf(business.getIsReferral()) == 1) {
            BusinessReferral businessReferral = businessReferralService.getBusinessReferralById(Long.valueOf(id));
            if (null == businessReferral) {
                throw new BizException("未找到该条转介绍商机！", 10001);
            }
            Date refTime = new Date();
            if (null != businessReferral.getReferralTime()) {
                refTime = businessReferral.getReferralTime();
            }
            // 获取转介绍拾回规则
            String days = ruleConfigService.getRuleConfigByMap(0l, "GZ_ZJS_SH");
            Integer pickUpRulesDay = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 90;
            Integer day = DateUtil.timeBetween(refTime, new Date(), "day");
            if (day > Integer.valueOf(pickUpRulesDay)) {
                // business.setAddTypeCode(BusinessConstant.BUS_ADD_TYPE_CODE_5);
                business.setIsReferral(0);
            }
        }

        // 在个人库新建
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);

        // 计算预计掉库时间
        setBusinessWillDropDate(business);
        repository.saveOrUpdate(business);

        //事业部库和无效库拾回
        if (BusinessConstant.BUS_STORE_DEPARTMENT.equals(location) || BusinessConstant.BUS_STORE_INVALID.equals(location)) {
            deleteDepartmentOrInvalidCustomer(business.getCustomerId(), user);
        }
        // 保存商机出入库类型的记录
        saveBusinessRecord(business, CustomerRecordConstant.BUS_GR_PICKUP, "拾回自跟进", user.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "",
                business.getFollowerName());
        return business.getBusinessStatus();
    }

    /**
     * 资源端拾回到二次待分配
     *
     * @param id
     * @return 返回拾回后的商机状态
     */

    public String pickUpToZyd(Long id, User user, String addType) {
        Business business = this.repository.get(Business.class, id);
        BizExceptionUtil.isException(null == business, "商机不存在");

        Integer location = business.getBusinessLocation();
        // 判断哪些库可以拾回 除开资源库、个人库、部门库、转介绍库，商机都可以拾回
        if (BusinessConstant.BUS_STORE_SOURCE.equals(location) || BusinessConstant.BUS_STORE_EMP.equals(location) || BusinessConstant.BUS_STORE_ORG.equals(location)
                || BusinessConstant.BUS_STORE_REFERRAl.equals(location) || BusinessConstant.BUS_STORE_FQ.equals(location)) {
            throw new BizException("商机当前所在库不能拾回！", 10001);
        }
        // 更改事业部
        BizExceptionUtil.isException(null == user.getOrgId(), "你还未设置资源部门，请联系管理员进行设置！");
        // 最新修改人、获取方式、计算成本改为CBJSFS_NO, 跟进次数清零。
        business.setUpdaterUser(user);
        business.setCreaterName(user.getName() + user.getLoginName());
        business.setCreaterId(user.getId());
        business.setCreaterOrgId(user.getOrgId());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);
        business.setAddTypeCode(addType);
        // business.setIsCost("CBJSFS_NO");
        business.setFollowTimes(0);
        // 已签单的状态不变，已退单的状态改为已签单，其他的状态都改成跟进中 2018年6月6日 10:43:27
        business.setBusinessStatus(BusinessConstant.BUS_WAIT_ALLOT_AGAIN); // 二次待分配
        //	business.setAddTypeCode(BusinessConstant.BUS_ADD_TYPE_CODE_1); // 商机新增方式
        business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ZYD_SHUIHUI);// 资源端拾回
        business.setIsReferral(0);
        business.setFollowerName(null);
        business.setFollowerName(null);
        business.setFirstFollowerOrganizationId(null);

        // opportunitytypeCode 为 COMMON_OPP_SH 最新分配时间 lastFollowTime lastLoseTime清空
        // lastLoseType清空 groupId清空 vip为0
        // business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_4);
        business.setLoseDeptTime(null);
        business.setNextFollowTime(null);
        business.setNextFollowContent(null);
        business.setBusinessStage(null);
        business.setGroupId(null);
        business.setIsVip(0);
        // 最后一次备注人名称 最后一次备注时间 最后一次备注记录内容
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setLastFollowTime(new Date());
        business.setLastFollowRecordContent("资源端拾回");
        business.setLastFollowRecordTime(new Date());
        business.setDxAllotUser(null);
        business.setDxAllotUserId(null);
        // 在个人库新建
        business.setBusinessLocation(BusinessConstant.BUS_STORE_SOURCE); // 资源库

        repository.saveOrUpdate(business);

        //事业部库和无效库拾回
        if (BusinessConstant.BUS_STORE_DEPARTMENT.equals(location) || BusinessConstant.BUS_STORE_INVALID.equals(location)) {
            deleteDepartmentOrInvalidCustomer(business.getCustomerId(), user);
        }

        // 保存商机出入库类型的记录
        saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE_ZYD_SHUIHUI, "资源端拾回", user.getId(), null, user.getId(), null, user.getOrgId(), "",
                user.getName() + user.getLoginName());
        return business.getBusinessStatus();
    }

    /**
     * 转介绍专员拾回
     *
     * @param id
     * @return 返回拾回后的商机状态 user 操作人 referralUser 转介绍人 reciveUser 接收人
     */

    public String pickUpToZjs(Long id, User user, User referralUser, User reciveUser, BusinessReferral businessReferral, String businessOrganizationId, String areaName) {
        Business business = this.repository.get(Business.class, id);
        BizExceptionUtil.isException(null == business, "商机不存在");

        Integer location = business.getBusinessLocation();
        // 判断哪些库可以拾回 除开资源库、转介绍库，商机都可以拾回
        if (BusinessConstant.BUS_STORE_SOURCE.equals(location) || BusinessConstant.BUS_STORE_REFERRAl.equals(location) || BusinessConstant.BUS_STORE_FQ.equals(location) || (BusinessConstant.BUS_STORE_ORG.equals(location) && CustomerRecordConstant.BUS_OPERATE_INVALID.equals(business.getBusinessOperate()))) {
            throw new BizException("商机当前所在库不能拾回！", 10001);
        }

        // 更改事业部
        BizExceptionUtil.isException(null == user.getOrgId(), "你还未设置资源部门，请联系管理员进行设置！");
        User oldFollower = userService.getUserById(business.getFollowerId());


        // 最新修改人、获取方式、计算成本改为CBJSFS_NO, 跟进次数清零。
        business.setUpdaterUser(user);
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);
        // business.setIsCost("CBJSFS_NO");
        business.setFollowTimes(0);
        business.setBusinessOrganizationId(NumberUtils.toLong(businessOrganizationId));
        business.setAddTypeCode(BusinessConstant.BUS_ADD_TYPE_CODE_7); // 转介绍
//		business.setBusinessStatus(BusinessConstant.BUS_WAIT_ALLOT_AGAIN); //二次待分配
//		business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE__REFERRAL_SHUIHUI); //转介绍拾回
        // opportunitytypeCode 为 COMMON_OPP_SH 最新分配时间 lastFollowTime lastLoseTime清空
        // lastLoseType清空 groupId清空 vip为0
        // business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_4);
        business.setLoseDeptTime(null);
        business.setNextFollowTime(null);
        business.setNextFollowContent(null);
        business.setBusinessStage(null);
        business.setGroupId(null);
        business.setIsVip(0);
        // 业务区域
        String[] area = areaName.split("/");
        if (area.length == 3) {
            business.setProvince(area[0].trim());
            business.setCity(area[1].trim());
            business.setArea(area[2].trim());
        } else if (area.length == 2) {
            business.setProvince(area[0].trim());
            business.setCity("");
        } else if (area.length == 1) {
            business.setProvince(area[0].trim());
            business.setCity("");
            business.setArea("");
        }
        business.setArea(business.getArea());
        business.setCity(business.getCity());
        business.setProvince(business.getProvince());
        business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_5);//转介绍
        // 最后一次备注人名称 最后一次备注时间 最后一次备注记录内容
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setLastFollowTime(new Date());
        business.setLastFollowRecordContent("转介绍专员拾回");
        business.setLastFollowRecordTime(new Date());
        business.setBusinessOrganizationId(business.getBusinessOrganizationId());
        BusinessReferral oldBusinessReferral = null;
        // 如果是转介绍商机 查询配置 配置内为转介绍 外是自开发商机 转介绍为0，
        if (null != business.getIsReferral() && Integer.valueOf(business.getIsReferral()) == 1) {
            oldBusinessReferral = businessReferralService.getBusinessReferralById(business.getId());
            if (oldBusinessReferral == null) {
                oldBusinessReferral = new BusinessReferral();
                oldBusinessReferral.setId(business.getId());
            }
        } else {
            oldBusinessReferral = new BusinessReferral();
            oldBusinessReferral.setId(business.getId());
        }
        oldBusinessReferral.setUpdaterUser(user);
        oldBusinessReferral.setReferralUserId(referralUser.getId());
        oldBusinessReferral.setReferralOrgId(referralUser.getOrgId());
        oldBusinessReferral.setReferralUserName(referralUser.getName() + referralUser.getLoginName());
        Long orgId = organizationService.getOrganizationDepartmentId(referralUser.getOrgId());
        oldBusinessReferral.setReferralOrganizationId(orgId);
        if (!TranslateMapUtil.translateOrgName(orgId).equals("null") && TranslateMapUtil.translateOrgName(orgId).length() > 0) {
            oldBusinessReferral.setReferralOrganizationName(TranslateMapUtil.translateOrgName(orgId));
        }
        oldBusinessReferral.setReceiveUserId(reciveUser.getId());
        oldBusinessReferral.setReceiveUserName(reciveUser.getName() + reciveUser.getLoginName());
        oldBusinessReferral.setReceiveOrgId(reciveUser.getOrgId());
        oldBusinessReferral.setReferralTime(businessReferral.getReferralTime());
        business.setFollowerName(reciveUser.getName() + reciveUser.getLoginName());
        business.setFollowerOrganizationId(reciveUser.getOrgId());
        business.setFirstFollowerOrganizationId(reciveUser.getOrgId());
        business.setFollowerId(reciveUser.getId());
        if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_HFYJ)) {
            oldBusinessReferral.setReferralAuditStatus(1);
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 待跟进
            business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);
            business.setBusinessOperate(CustomerRecordConstant.BUS_PICKUP);//

        } else if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_FFTC)) {
            // 进入质检待审核
            business.setBusinessStatus(BusinessConstant.BUS_STATUS_WAIT_FOLLOW);// 质检待审核设置待跟进
            business.setBusinessLocation(BusinessConstant.BUS_STORE_REFERRAl);// 转介绍库
            business.setBusinessOperate(CustomerRecordConstant.BUS_1009);// 当前操作为质检待审核
            oldBusinessReferral.setReferralAuditStatus(0);
            business.setBusinessLocation(BusinessConstant.BUS_STORE_REFERRAl);
        }
        oldBusinessReferral.setRewardWay(businessReferral.getRewardWay());
        oldBusinessReferral.setReferralRed(businessReferral.getReferralRed());
        oldBusinessReferral.setPerformanceProportion(businessReferral.getPerformanceProportion());
        oldBusinessReferral.setTcProportion(businessReferral.getTcProportion());
        oldBusinessReferral.setIsReceive(1);
        oldBusinessReferral.setCreateType(1);
        oldBusinessReferral.setReferralType(businessReferral.getReferralType());
        business.setIsReturn("BUS_3_1");
        oldBusinessReferral.setCreateUser(user);
        oldBusinessReferral.setReturnNum(1);
        // 在个人库新建
        business.setIsReferral(1);// 是否转介绍
        // 计算预计掉库时间
        setBusinessWillDropDate(business);
        business.setDistributionTime(new Date());
        repository.saveOrUpdate(business);
        repository.saveOrUpdate(oldBusinessReferral);

        //如果在个人库，提醒商务。保存商机出入库类型的记录

        if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_HFYJ)) {
            if (BusinessConstant.BUS_STORE_EMP.equals(location)) {
                String[] msgs = {business.getNo(), user.getName(), user.getLoginName(), DateUtil.dateToString(new Date())};
                messageService.sendMessageReady(oldFollower, referralUser, msgs, "SJ_ZJS_SH");
                saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE__REFERRAL_SHUIHUI, "转介绍专员拾回并分配", user.getId(), oldFollower.getId(), reciveUser.getId(), oldFollower.getOrgId(), reciveUser.getOrgId(), oldFollower.getName() + oldFollower.getLoginName(),
                        reciveUser.getName() + reciveUser.getLoginName());
            } else {
                saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE__REFERRAL_SHUIHUI, "转介绍专员拾回并分配", user.getId(), null, reciveUser.getId(), null, reciveUser.getOrgId(), null,
                        reciveUser.getName() + reciveUser.getLoginName());
            }

        } else if (businessReferral.getRewardWay().equals(BusinessConstant.REFERRAL_AWARD_WAY_FFTC)) {

            if (BusinessConstant.BUS_STORE_EMP.equals(location)) {
                saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE__REFERRAL_SHUIHUI, "转介绍专员拾回", user.getId(), oldFollower.getId(), null, oldFollower.getOrgId(), null, oldFollower.getName() + oldFollower.getLoginName(),
                        null);
            } else {
                saveBusinessRecord(business, CustomerRecordConstant.BUS_OPERATE__REFERRAL_SHUIHUI, "转介绍专员拾回", user.getId(), null, null, null, null, null,
                        null);
            }
        }

        //事业部库和无效库拾回
        if (BusinessConstant.BUS_STORE_DEPARTMENT.equals(location) || BusinessConstant.BUS_STORE_INVALID.equals(location)) {
            deleteDepartmentOrInvalidCustomer(business.getCustomerId(), user);
        }

        //接收人
        sendBusinessMsg(reciveUser, user, "SJ_ZJS_0003", business.getNo(), DateUtil.dateToString(business.getDistributionTime()));
        //转介绍人
        sendBusinessMsg(referralUser, reciveUser, "SJ_ZJS_0001", business.getNo(), reciveUser.getName() + reciveUser.getLoginName());


        // 给电销分配人员推送消息
        if (business.getDxAllotUserId() != null) {
            String[] msgs = {business.getNo(), reciveUser.getName(), reciveUser.getLoginName()};
            messageService.sendMessageReady(userService.getUserById(business.getDxAllotUserId()), reciveUser, msgs, "SJ_ZJS_JD");
        }
        setBusinessWillDropDate(business);
        return business.getBusinessStatus();
    }

    /**
     * 电销分配记录
     *
     * @param map
     * @return
     */
    public List<Map> listDxAllotRecordByMap(Map map) {
        map.put("recordType", CustomerRecordConstant.BUS_OPERATE_SHANGMEN);
        return businessDao.listDxAllotRecordByMap(map);
    }

    /**
     * 电销分配记录条数
     *
     * @param map
     * @return
     */
    public Integer countDxAllotRecordByMap(Map map) {
        map.put("recordType", CustomerRecordConstant.BUS_OPERATE_SHANGMEN);
        return businessDao.countDxAllotRecordByMap(map);
    }


    public void deleteDepartmentOrInvalidCustomer(Long customerId, User user) {
        DepartmentCustomer dc = departmentCustomerService.getDepartmentCustomerByCustomerId(customerId);
        if (null != dc) {

            if (dc.getPushTime() != null) {
                Map whiteListMap = new HashMap();
                String pushMonth = DateUtil.dateToString(dc.getPushTime(), "yyyy-MM-dd");
                whiteListMap.put("month", pushMonth);
                whiteListMap.put("deptCusId", dc.getId());
                // 查询所有白名单表
                List<WhiteList> wl = whiteListService.queryWhiteListByParam(whiteListMap);
                if (null != wl && wl.size() > 0) {
                    for (WhiteList whiteList : wl) {
                        whiteList.setUpdaterUser(user);
                        Integer status = whiteList.getPushUserId().longValue() == user.getId().longValue() ? 2 : 3;
                        whiteList.setStatus(status);
                        repository.saveOrUpdate(whiteList);
                    }
                }
            }
            repository.delete(dc);
        }
        // 删除无效库中客户相关的数据
        Map imap = new HashMap();
        imap.put("customerId", customerId);
        businessDao.deleteInvalidCustomerByMap(imap);
    }


    /**
     * 抢商机
     *
     * @param id
     * @return 返回拾回后的商机状态
     */

    public String grapToFollow(Long id, User user) {
        Business business = this.repository.get(Business.class, id);
        BizExceptionUtil.isException(null == business, "商机不存在");

        Integer oldLocation = business.getBusinessLocation();
        User oldFollower = userService.getUserById(business.getFollowerId());
        // 更改事业部
        BizExceptionUtil.isException(null == user.getOrgId(), "你还未设置资源部门，请联系管理员进行设置！");
        Long deptId = organizationService.getOrganizationDepartmentId(user.getOrgId());
        BizExceptionUtil.isException(-1 == deptId, "未找到你当前所在事业部，请联系管理员进行设置！");

        // 判断库容量是否已经满了，满了则不能接单
        Map numMap = new HashMap();
        numMap.put("followerId", user.getId());
        isMoreThanSybNum(numMap, organizationService.getOrganizationDepartmentId(user.getOrgId()));

        if (null != oldLocation && !BusinessConstant.BUS_STORE_EMP.equals(oldLocation)) {
            throw new BizException("商机不在个人库，不用抢单！", 10001);
        }
        if (null != user.getOrgId()) {
            business.setBusinessOrganizationId(deptId);// 所属事业部
        }

        // 最新修改人、获取方式、计算成本改为CBJSFS_NO, 跟进次数清零。
        business.setUpdaterUser(user);
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);
        // business.setIsCost("CBJSFS_NO");
        business.setFollowTimes(0);
        // 已签单的状态不变，已退单的状态改为已签单，其他的状态都改成跟进中 2018年6月6日 10:43:27

		/*if (!BusinessConstant.BUS_STATUS_SIGNED.equals(business.getBusinessStatus())) {
			if (BusinessConstant.BUS_STATUS_ORDER_BACK.equals(business.getBusinessStatus()) || BusinessConstant.BUS_STATUS_ORDER_SUCCESSED.equals(business.getBusinessStatus())) {
				business.setBusinessStatus(BusinessConstant.BUS_STATUS_SIGNED);
			} else {
				business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);
			}
		}*/

        // opportunitytypeCode 为 COMMON_OPP_SH 最新分配时间 lastFollowTime lastLoseTime清空
        // lastLoseType清空 groupId清空 vip为0
        // business.setOpportunitytypeCode(BusinessConstant.BUS_OPP_4);
        business.setLoseDeptTime(null);
        business.setNextFollowTime(null);
        business.setNextFollowContent(null);
        business.setBusinessStage(null);
        business.setGroupId(null);
        business.setIsVip(0);
        // 最后一次备注人名称 最后一次备注时间 最后一次备注记录内容
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setLastFollowTime(new Date());
        business.setLastFollowRecordContent("抢商机");
        business.setLastFollowRecordTime(new Date());
        // 更新跟进人相关信息
        business.setBusinessOperate(CustomerRecordConstant.BUS_GRAP);
        business.setFollowerId(user.getId());
        business.setFollowerName(user.getName() + user.getLoginName());
        business.setFollowerOrganizationId(user.getOrgId());
        business.setDistributionTime(new Date());

        // 如果是转介绍商机 查询配置 配置内为转介绍 外是自开发商机 转介绍为0，
        if (null != business.getIsReferral() && Integer.valueOf(business.getIsReferral()) == 1) {
            BusinessReferral businessReferral = businessReferralService.getBusinessReferralById(Long.valueOf(id));
            if (null == businessReferral) {
                throw new BizException("未找到该条转介绍商机！", 10001);
            }
            Date refTime = new Date();
            if (null != businessReferral.getReferralTime()) {
                refTime = businessReferral.getReferralTime();
            }
            // 获取转介绍拾回规则
            String days = ruleConfigService.getRuleConfigByMap(0l, "GZ_ZJS_SH");
            Integer pickUpRulesDay = StringUtils.isNotEmpty(days) ? Integer.parseInt(days) : 90;
            Integer day = DateUtil.timeBetween(refTime, new Date(), "day");
            if (day > Integer.valueOf(pickUpRulesDay)) {
                // business.setAddTypeCode(BusinessConstant.BUS_ADD_TYPE_CODE_5);
                business.setIsReferral(0);
            }
        }

        // 在个人库新建
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);

        // 计算预计掉库时间
        setBusinessWillDropDate(business);
        repository.saveOrUpdate(business);

        //对客户的其他商机掉库
        List<Map> businessList = this.getBuinesssListByRule(business, "order");
        for (Map oldMap : businessList) {
            if (null != oldMap.get("id") && business.getId().longValue() != Long.parseLong(oldMap.get("id").toString())) {
                Business oldBusiness = getBusinessById(Long.parseLong(oldMap.get("id").toString()));
                Integer location = oldBusiness.getBusinessLocation();
                if (BusinessConstant.BUS_STORE_EMP.equals(oldBusiness.getBusinessLocation())) {

                    User oldBusinessFollower = userService.getUserById(oldBusiness.getFollowerId());
                    Customer customer = customerService.findCustomerById(business.getCustomerId());
                    //个人库，写出库记录
                    saveBusinessRecord(oldBusiness, CustomerRecordConstant.BUS_ORDER_DROP, "客户被签单，商机强制掉库", user.getId(), oldBusinessFollower.getId(), null, oldBusinessFollower.getOrgId(), null,
                            oldBusinessFollower.getName() + oldBusinessFollower.getLoginName(), "");
                    String[] msgs = {customer.getName(), customer.getNo(), user.getName(), user.getLoginName(), business.getNo(), oldBusiness.getNo()};
                    messageService.sendMessageReady(oldBusinessFollower, user, msgs, "SJ_QD_001");
                }
                oldBusiness.setBusinessLocation(BusinessConstant.BUS_STORE_FQ);
                oldBusiness.setBusinessOperate(CustomerRecordConstant.BUS_ORDER_DROP);
                //事业部库和无效库拾回
                if (BusinessConstant.BUS_STORE_DEPARTMENT.equals(location) || BusinessConstant.BUS_STORE_INVALID.equals(location)) {
                    deleteDepartmentOrInvalidCustomer(business.getCustomerId(), user);
                }
                repository.saveOrUpdate(oldBusiness);
            }
        }

        // 保存商机出入库类型的记录
        saveBusinessRecord(business, CustomerRecordConstant.BUS_GRAP, "抢商机", user.getId(), oldFollower.getId(), business.getFollowerId(), oldFollower.getOrgId(), business.getFollowerOrganizationId(), oldFollower.getName() + oldFollower.getLoginName(),
                business.getFollowerName());

        String[] msgs = {business.getNo(), user.getName(), user.getLoginName(), DateUtil.dateToString(new Date())};
//		messageService.sendMessage(oldFollower, user, msgs, "SJ_GRAP");
        messageService.sendMessageReady(oldFollower, user, msgs, "SJ_GRAP");

        return business.getBusinessStatus();
    }

    public List<Map> getBuinesssListByRule(Business business, String type) {
        Map existed = new HashMap();
        if (null != business && StringUtils.isNotBlank(business.getTypeCode())) {
            TreeBook tb = treeBookService.queryTreeBookByCode(business.getTypeCode());
            if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_2)) { //事业部
                existed.put("businessOrganizationId", String.valueOf(business.getBusinessOrganizationId()));
            } else if (tb.getExt5().equals(BusinessConstant.BUS_REPEAT_1)) {//分公司
                //获取所有分公司下面的事业部，现在只用当前事业部
                existed.put("businessOrganizationId", String.valueOf(business.getBusinessOrganizationId()));
            } else {//全集团

            }
        }

        existed.put("customerId", business.getCustomerId());
        existed.put("notInBusinessLocation", "'" + BusinessConstant.BUS_STORE_SOURCE + "','" + BusinessConstant.BUS_STORE_REFERRAl + "'");
        existed.put("notbusinessOperate", "'" + CustomerRecordConstant.BUS_OPERATE_INVALID + "'");
        //existed.put("notInBusinessStatus","'"+BusinessConstant.BUS_STATUS_SIGNED+"','"+BusinessConstant.BUS_STATUS_ORDER_SUCCESSED+"','"+BusinessConstant.BUS_STATUS_ORDER_BACK+"'");
        List<Map> list = businessDao.listBusinessByMap(existed);
        return list;
    }


    public List<Map> dxSharedBusiness(Map existed, Customer customer, String ids) {
        existed.put("customerId", customer.getId());
        existed.put("notInBusinessLocation", String.valueOf(BusinessConstant.BUS_STORE_SOURCE + "," + BusinessConstant.BUS_STORE_INVALID + ",6"));
        existed.put("businessOrganizationId", ids);
        List<Map> list = businessDao.listBusinessByMap(existed);
        return list;
    }

    /**
     * 电销客户共享库列表查询
     *
     * @param params
     * @return
     */
    public List<Map> queryDxCusShareList(Map params) {
        String areaName = params.get("areaName") == null ? "" : params.get("areaName").toString();
        params.put("province", "");
        params.put("city", "");
        params.put("area", "");
        if (!"".equals(areaName)) {
            // 业务区域
            String[] area = areaName.split("/");
            if (area.length == 3) {
                params.put("province", area[0].trim());
                params.put("city", area[1].trim());
                params.put("area", area[2].trim());
            } else if (area.length == 2) {
                params.put("province", area[0].trim());
                params.put("city", area[1].trim());
            } else if (area.length == 1) {
                params.put("province", area[0].trim());
            }
        }
        return businessDao.queryDxCusShareList(params);
    }

    /**
     * 电销客户共享库列表查询总数
     *
     * @param params
     * @return
     */
    public int queryDxCusShareListCount(Map params) {
        String areaName = params.get("areaName") == null ? "" : params.get("areaName").toString();
        params.put("province", "");
        params.put("city", "");
        params.put("area", "");
        if (!"".equals(areaName)) {
            // 业务区域
            String[] area = areaName.split("/");
            if (area.length == 3) {
                params.put("province", area[0].trim());
                params.put("city", area[1].trim());
                params.put("area", area[2].trim());
            } else if (area.length == 2) {
                params.put("province", area[0].trim());
                params.put("city", area[1].trim());
            } else if (area.length == 1) {
                params.put("province", area[0].trim());
            }
        }
        return businessDao.queryDxCusShareListCount(params);
    }


    /**
     * 电销客户共享库 拾回
     *
     * @param id
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void dxCusSharePickUp(Long id, User user) {
        //查询，判断是否已拾回，拾回判重，拾回并建商机
        Map m = new HashMap();
        m.put("id", id);
        DxCustomerShareEntity dxCustomerShareEntity = businessDao.queryDxCusShareById(m);
        if (dxCustomerShareEntity == null) {
            throw new BizException("该资源不存在，请刷新后再试！", 10001);
        }
        if (!"0".equals(dxCustomerShareEntity.getIsPickup())) {
            throw new BizException("该资源已被拾回，请刷新后再试！", 10001);
        }
//		String ids = "";
//		//获取字典中电销事业部id配置
//		TreeBook treeBook = treeBookService.queryTreeBookByCode("CUS-SHARING");
//		if (null != treeBook && StringUtils.isNotEmpty(treeBook.getExt1())) {
//			List<String> codes = Arrays.asList(treeBook.getExt1().split(","));
//			for (String code:codes) {
//				ids = ids + "," + code;
//			}
//		}
//		if(ids.isEmpty()){throw new BizException("未配置电销事业部，无法拾回",10001);}
//		ids = ids.substring(1);


        Business business = new Business();
        business.setId(DggKeyWorker.nextId());
        business.setCreateUser(user);
        business.setNo(billNumberService.updateBillNumberByCode("SJ"));// 商机单据号);
        business.setFollowerId(user.getId());
        business.setFollowerName(user.getName() + user.getLoginName());
        business.setCustomerId(dxCustomerShareEntity.getCustomerId());
        business.setCustomerName(dxCustomerShareEntity.getCustomerName());
        business.setCustomerNo(dxCustomerShareEntity.getCustomerNo());
        business.setCustomerPhone(dxCustomerShareEntity.getCustomerNumber());
        business.setCustomerWay(dxCustomerShareEntity.getCustomerNumberType());
        business.setTypeCode(dxCustomerShareEntity.getTypeCode());
        business.setBusinessStatus(BusinessConstant.BUS_STATUS_FOLLOWING);//跟进中
        business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_DX_CUS_SHARE_PICKUP);//电销客户共享库拾回
        BizExceptionUtil.isException(null == user.getOrgId(), "你还未设置资源部门，请联系管理员进行设置！");
        business.setFollowerOrganizationId(user.getOrgId());
        Long deptId = organizationService.getOrganizationDepartmentId(user.getOrgId());
        BizExceptionUtil.isException(-1 == deptId, "未找到你当前所在事业部，请联系管理员进行设置！");
//		if(!ids.contains(deptId+"")){throw new BizException("用户为非电销事业部用户，无法拾回",10001);}
        business.setBusinessOrganizationId(deptId);

        business.setOpportunitytypeCode(BusinessConstant.BUS_WAY_CODE_6);
        business.setOriginCode(dxCustomerShareEntity.getOriginCode());
        business.setOrigincodeType(dxCustomerShareEntity.getOriginType());
        business.setBusinessSourceCode(dxCustomerShareEntity.getBusinessSourceCode());
        business.setExtensionCode(dxCustomerShareEntity.getExtensionCode());
        business.setWayCode(BusinessConstant.BUS_WAY_CODE_6);//拾回
        business.setLastFollowRecordUser(user.getName() + user.getLoginName());
        business.setLastFollowRecordTime(new Date());
        business.setLastFollowRecordContent("共享库拾回");
        business.setDistributionTime(new Date());
        business.setLastFollowTime(new Date());
        business.setProvince(dxCustomerShareEntity.getProvince());
        business.setCity(dxCustomerShareEntity.getCity());
        business.setArea(dxCustomerShareEntity.getArea());
        business.setKeyWord(dxCustomerShareEntity.getKeyWord());
        business.setUrl(dxCustomerShareEntity.getUrl());
        business.setAddTypeCode(dxCustomerShareEntity.getAddTypeCode());
        business.setFollowTimes(1);//跟进次数
        business.setBusinessLocation(BusinessConstant.BUS_STORE_EMP);//个人库
        setBusinessWillDropDate(business);
//        business.setWillDropTime(null);
//        business.setWillDropCode(null);
        Customer customerDTO = new Customer();
        customerDTO.setId(dxCustomerShareEntity.getCustomerId());
        customerDTO.setNo(dxCustomerShareEntity.getCustomerNo());
        customerDTO.setName(dxCustomerShareEntity.getCustomerName());
        customerDTO.setCustomerPhone(dxCustomerShareEntity.getCustomerNumber());
        customerDTO.setContactWay(dxCustomerShareEntity.getCustomerNumberType());
        //拾回判重
        List<Map> list = dxSharedBusiness(new HashMap(), customerDTO, deptId + "");
        if (list.size() > 0) {
            throw new BizException("已存在相同客户商机，无法拾回", 10001);
        }
        //新建商机
        repository.save(business);
        //保存出入库记录
        saveBusinessRecord(business, business.getBusinessOperate(), "电销客户共享库拾回", user.getId(), null, business.getFollowerId(), null, business.getFollowerOrganizationId(), "", business.getFollowerName());

        // 写入新增商机的备注日志
        //修改状态
        Map isPickUp = new HashMap();
        isPickUp.put("isPickup", "1");
        isPickUp.put("id", dxCustomerShareEntity.getId());
        businessDao.updateDxCusShareById(isPickUp);
    }

}
